Alex Sidorenko AvatarAlex Sidorenko

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?

Updating the state of a sibling component in React

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.

Lift state to the common parent

Now, let's pass it back as a prop to Component C.

Pass state back as a prop

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.

Pass state updater

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.

Updating the state of a component from the sibling component via parent

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.


Follow me on 饾晱 for short videos about Next.js

饾晱 Follow for more