24 Nov 2022
How to update the state of a sibling component in React?
Let's say we have a button in the left panel of a UI that changes some state in the right panel, and those panels are sibling React components.
How can we achieve this when React doesn't allow us to pass props between components that 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's 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're back at square one, but the state is controlled by Component A instead of Component C.
Next, let's pass another prop, this time to Component B. This prop will hold a function that updates our state. We'll 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 the techniques from this article to fix it. Remember that when lifting the state up, we need to lift all the code that handles this state as well.