๐Sometimes, two or more React components need to share the same data. In such cases, we lift the state up to their common parent component so it can manage and pass the data as props.
๐ฏ Why do we lift state up?
โข To avoid duplicate state
โข To sync UI across multiple components
โข To make one source of truth
๐จโ๐ฉโ๐ง Example:
function Parent() {
const [count, setCount] = useState(0);
return (
<>
<Display count={count} />
<Controls setCount={setCount} />
</>
);
}
function Display({ count }) {
return <h2>Count: {count}</h2>;
}
function Controls({ setCount }) {
return <button onClick={() => setCount(prev => prev + 1)}>Increment</button>;
}
๐ก The parent owns the state, and passes it down to children using props.
This pattern keeps your React app organized, especially when multiple components rely on the same state.
Top comments (0)