Sharing State
Sharing state means lifting state up to a shared parent. The parent holds the state, and the children receive it through props.
State lives in the parent
The parent creates the state once.
const [count, setCount] = useState(0);Both children receive it
Each Display shows the same count.
<>
<Display count={count} />
<Display count={count} />
</>The parent passes the setter too
A child handler can change the shared state.
function handleAdd() {
setCount(count + 1);
}Example
import { useState } from 'react';
function Display(props) {
return <p>Count: {props.count}</p>;
}
export default function App() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<Display count={count} />
<Display count={count} />
<button onClick={handleClick}>Add 1</button>
</div>
);
}Key points
- Two children sometimes need the same value.
- State in one child cannot reach the other child.
- Move the state to their shared parent.
- The parent passes the value to both children.
- The parent can also pass the setter down as a prop.
In this example, Display takes props and shows the count. App starts count at 0. handleClick calls setCount with count + 1. App renders Display twice with the same count. App also returns a button. A click runs handleClick. React renders again, and both paragraphs show Count: 1.
Note
Lift the state to the closest shared parent.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where should state live when two children need the same value?