Let’s say we have a button in the left panel of UI that changes some state in the right panel, and those panels are sibling React components.
How can we do that if React doesn’t allow us to pass props between components which don’t have a direct parent/child relationship?
Lifting the state up
Since siblings in React can’t access each other’s state, we need to lift the state up to the common parent and then pass it back to both children as props. Sounds complicated? Here is a simple visual step by step guide 👇
First, let’s lift the state up by removing it from Component C and adding it to Component A.
Now, let’s pass it back as a prop to Component C.
At this point, we are back at square one, but the state is controlled by Component A instead of Component C.
Now let’s pass another prop, this time to Component B. This prop will hold a function that updates our state. We will set this prop as the click handler for our button.
That’s it! Now when we click the button in Component B, it triggers a state update in the parent Component A, which gets reflected in Component C since we pass it as a prop.
Coding Challenge 🙌
The app in this Code Sandbox doesn’t work as expected. Try to apply techniques from the article to fix it. Don’t forget that when lifting the state up, we need to lift all the code that handles this state as well.