Search code examples
reactjsstatereact-propssetstate

REACT: How do you set a child component's state to its parent's state?


I would like the child component's state to update as the parent component's state updates. Any changes to parent state variables should be reflected in the child's state. How can I do this?

Thanks!

Edit:

My components are arranged in the following manner. I would like to access the parent's state from Child 2. By setting the Child 1 state to the parent's state, I will be able to do this.

Parent->Child 1->Child 2


Solution

  • State And Props

    React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

    the data flow in react is “unidirectional” or “top-down”, Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.

    If you imagine a component tree as a waterfall of props, each component’s state is like an additional water source that joins it at an arbitrary point but also flows down.

    This is why the state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it. @reactjs

    Therefore, You Should pass the state to the child component, also known as prop.

    Edit:

    the hierarchy will be like this: App(state - date) => Child1(prop date, passing the same prop to the next child) => Child2(getting date from his parent - Child1)

    Example (based on Class Components):

    <App>:

    The root of the app.

    <ClockList date={this.state.date} />
    

    <ClockList>:

    notice we are using props

    <Clock date={this.props.date} />
    

    <Clock>:

    import React from "react";
    
    const Clock = (props) => {
      // Object Destructuring can also be done in the function itself.
      const { date } = props;
      return (
        <div className="container">
          <p>{date}</p>
        </div>
      );
    };
    
    export default Clock;