π€ Lifting State Up
When multiple components need to share and synchronize state, itβs often best to **move the state up** to their closest common ancestor β a pattern known as Lifting State Up.
π― Why Lift State?
- Coordinate data between sibling components
- Keep a single source of truth
- Make data flow predictable and easier to debug
π¦ Example Scenario
Imagine two components: one updates a value, and the other displays it. Instead of storing state in both, you lift it up to a parent.
// Parent Component
function Parent() {
const [count, setCount] = React.useState(0);
return (
<>
<Counter value={count} />
<Increment onClick={() => setCount(count + 1)} />
</>
);
}
function Counter({ value }) {
return <p>Count: {value}</p>;
}
function Increment({ onClick }) {
return <button onClick={onClick}>+1</button>;
}
β Benefits
- Ensures consistent state across components
- Improves control and maintainability
- Makes debugging easier with a single source of truth
π Summary
- Shared state should live in the nearest common parent
- Child components communicate via props and callbacks
- Lifting state up helps avoid data duplication