DEV Community

Lori "Lei" Boyd
Lori "Lei" Boyd

Posted on

Lifting State With React

Lifting the state allows your sibling components to share a single source of truth. In a hierarchy tree, components can only inherit data from their parent components.

Lets walk through this test application.

Alt Text

Our hierarchy looks like this.

Alt Text

We have a parent component with two children components. Our goal is to make our Child component be a button that changes the color of Child2's text.

Alt Text

In our Parent component, we initialize the state with a key of color and value of 'blue'.

Because we want to change the sate we have a function in the Parent component that does just that. It's a conditional that checks if the this.state.color is equal to 'blue'. If that is true, we set the sate to 'red' and if false, we set the state to back to 'blue'

Next, we have a render function that returns both Child and Child2. Child inherits the reference to this.setColor, and Child2 inherits this.state.color.

Child does one thing. It renders a button with an event listener. Our callback function for the click event is the function that Child inherited from Parent. We access this by using the properties given via this.props.changeColor.

Alt Text

So now every time Child's button is clicked, the function in the Parent component is invoked and changes the state.

Since we are rendering our Child2 component in our Parent as well, every time we change the state, Parent gets re-rendered which inturn re-renders each child.

This is where the magic happens.

Alt Text

Now let's look at Child2.

Alt Text

Child2's only job is to render some text. We have our p tag with an inline style set to Child2's color property. When Parent gets re-rendered by setState Child2 get's re-rendered with the new state as its new prop!

Recap

Every time Child's button is clicked, Child invokes the instance method defined in the Parent. That instance method changes the state based on its contents and triggers a re-render. Child2 is now re-rendered with the new state as an inherited property.

Alt Text

Top comments (2)

Collapse
 
iqramqra profile image
Iqra Masroor

This is so helpful!

Collapse
 
loripb profile image
Lori "Lei" Boyd

Glad I could help!