Lifting state helps share information between components in React. It moves state up to a common parent so multiple parts can use it.
0
0
Why lifting state is needed in React
Introduction
When two sibling components need to access the same data.
When a child component needs to update data that affects another child.
When you want to keep data consistent across different parts of the UI.
When you want to avoid duplicating state in multiple components.
When you want a single source of truth for shared data.
Syntax
React
import React, { useState } from 'react'; function Parent() { const [sharedState, setSharedState] = useState(initialValue); return ( <> <ChildA state={sharedState} setState={setSharedState} /> <ChildB state={sharedState} /> </> ); }
The state is declared in the parent component.
State and its updater function are passed down as props to children.
Examples
Parent holds the count state. Incrementer can change it, Display shows it.
React
import React, { useState } from 'react'; function Parent() { const [count, setCount] = useState(0); return ( <> <Incrementer count={count} setCount={setCount} /> <Display count={count} /> </> ); }
InputBox updates text, Preview shows the same text. State is lifted to Parent.
React
import React, { useState } from 'react'; function Parent() { const [text, setText] = useState(''); return ( <> <InputBox text={text} setText={setText} /> <Preview text={text} /> </> ); }
Sample Program
This example shows lifting state to Parent so both ColorPicker and ColorDisplay share the same color value. Changing the dropdown updates the displayed color.
React
import React, { useState } from 'react'; function Parent() { const [color, setColor] = useState('red'); return ( <div> <h2>Choose a color:</h2> <ColorPicker color={color} setColor={setColor} /> <ColorDisplay color={color} /> </div> ); } function ColorPicker({ color, setColor }) { return ( <select value={color} onChange={e => setColor(e.target.value)} aria-label="Select color"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select> ); } function ColorDisplay({ color }) { return <p>The selected color is <strong>{color}</strong>.</p>; } export default Parent;
OutputSuccess
Important Notes
Always lift state to the closest common parent of components that need it.
Passing state down as props keeps components in sync.
Too much lifting can make code complex; consider context or state libraries for bigger apps.
Summary
Lifting state moves shared data up to a parent component.
This allows multiple child components to read and update the same state.
It keeps data consistent and avoids duplication.