Lifting State: How to Make Neighbor Components Friends?
In React, data flows top to bottom. But what if two neighbor components need the same data? For example, Input Field writes text, and Preview should display it immediately.
1. Problem: Walls Between Components
By default, each component is an autonomous fortress. Input has no access to what happens inside Preview. If you create useState inside Input, that data will " die " there.
2. Solution: Lifting State Up
We move useState from children to their nearest common Parent.
Now the Parent becomes the " Keeper of Truth " (Single Source of Truth).
3. Analogy: TV and Remote
Imagine the Parent is the TV, and the Child is the Remote.
- The Remote has no screen and doesn't store movies.
- But the Remote has buttons that the TV gave it.
- When you press a button on the Remote (call a callback function), the TV receives the signal and itself changes the channel.
- As soon as the channel on the TV changes, everyone watching it (other child components) sees the new picture.
4. How Does This Look in Code?
The parent passes the child two things via props:
- Value: So the child knows what to show.
- Function: So the child can " ask " the parent to change this value.
function Parent() {
const [name, setName] = useState('');
return (
<>
{/* Pass setName function as onNameChange prop */}
<ChildInput value={name} onNameChange={setName} />
{/* Simply pass value for display */}
<ChildDisplay text={name} />
</>
);
}
5. Why Is This Cool?
This pattern makes your application predictable. If data behaves strangely, you don't search for bugs throughout the project. You go to the single Parent component where this useState lives and check the logic there.
Lifting state, you turn a chaotic set of elements into a neat, synchronized system.