16. What is state lifting in React?

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.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.