28. Lifting State Up
Sharing Data Between Components
React data flow is strictly unidirectional: it only flows Top-Down (from Parent to Child) via props. But what happens if two sibling components (like a <ProductList /> and a <CartSummary />) need to share the exact same data? Siblings cannot pass props to each other. The solution is Lifting State Up.
The Architecture of Shared State
If Component A and Component B need to access the same state, you must physically move the useState hook out of Component A, and move it up to their closest common parent component. Then, the parent passes the state down to both children as props.
Inverse Data Flow
While data (the value) flows Top-Down, we often say actions flow Bottom-Up. Because the parent passes the setter function (setSharedText) down to the child as a prop, the child can call that function. When the child calls the setter, it actually triggers the state change in the parent, which forces both children to re-render with the new data.
When is Lifting State Up Bad?
If you lift state too high up the tree (e.g., putting all your state in the main <App /> component), every time a user types a single letter, the entire application will re-render, destroying performance. This "Prop Drilling" problem is why Global State tools like Context API and Zustand exist for large apps.
Knowledge Check
Ready to test your understanding of 28. Lifting State Up?