What are the ways to update the state of a parent component in React

0 votes
With the help of code examples can you tell me What are the ways to update the state of a parent component in React?
Feb 12 in Node-js by Nidhi
• 11,580 points
62 views

1 answer to this question.

0 votes

Child components can update the state of their parent components through a pattern known as "lifting state up." This involves passing a function from the parent to the child as a prop, allowing the child to invoke this function to modify the parent's state.

Implementing State Updates from Child to Parent:

Define the State and Handler in the Parent Component:

Initialize the state in the parent component.

Create a function that updates this state.

Pass the function to the child component as a prop.

import React, { useState } from 'react';

import ChildComponent from './ChildComponent';

const ParentComponent = () => {

  const [parentState, setParentState] = useState('');

  const updateParentState = (value) => {

    setParentState(value);

  };

  return (

    <div>

      <ChildComponent onUpdate={updateParentState} />

      <p>Parent State: {parentState}</p>

    </div>

  );

};

export default ParentComponent;

Invoke the Handler in the Child Component:

Receive the function via props in the child component.

Call this function when an event occurs (e.g., a button click) to update the parent's state.

import React from 'react';

const ChildComponent = ({ onUpdate }) => {

  const handleClick = () => {

    onUpdate('New Value from Child');

  };

  return (

    <div>

      <button onClick={handleClick}>Update Parent State</button>

    </div>

  );

};

export default ChildComponent;
answered Feb 21 by kavya

Related Questions In Node-js

0 votes
1 answer

What are the approaches to testing in React?

Testing in React ensures your components, logic, ...READ MORE

answered Dec 12, 2024 in Node-js by Navya
100 views
0 votes
1 answer

What methods are available to force a component to re-render when using React hooks?

Here are the primary methods available to ...READ MORE

answered Feb 23 in Node-js by Kavya
72 views
0 votes
0 answers
0 votes
1 answer

What distinguishes the loadingIndicatorSource prop from the defaultSource prop in React Native?

Property loadingIndicatorSource defaultSource Purpose Placeholder during remote image loading. Placeholder before load ...READ MORE

answered Feb 21 in Node-js by kavya
68 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How are default props declared in a React functional component?

In React functional components, default prop values ...READ MORE

answered Feb 21 in Node-js by kavya
58 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP