State lifting in React involves moving state to the closest common ancestor of two or more components that need to share this state. This allows for organized state sharing between components.
Example of state lifting: Let's assume we have two child components that need to share the same state.
function ParentComponent() { const [sharedState, setSharedState] = useState(''); return ( <div> <ChildComponentA sharedState={sharedState} setSharedState={setSharedState} /> <ChildComponentB sharedState={sharedState} /> </div> ); } function ChildComponentA({ sharedState, setSharedState }) { return ( <input type="text" value={sharedState} onChange={(e) => setSharedState(e.target.value)} /> ); } function ChildComponentB({ sharedState }) { return ( <p>{sharedState}</p> ); }
In this example, the sharedState
state is lifted to ParentComponent
, allowing it to be shared between ChildComponentA
and ChildComponentB
.