What is Lifting State Up in React?
Lifting State Up is a pattern in React where you move the shared state to the closest common ancestor of components that need to access or modify it. Instead of maintaining separate copies of the same state in multiple components, the state is "lifted up" to a parent component, which then passes it down via props.
This approach helps in:
- Keeping the state synchronized across different components.
- Avoiding duplication and inconsistency of data.
- Managing a single source of truth, making the application easier to debug and maintain.
Example:
Suppose you have two sibling components that need to communicate or share a piece of data. Instead of each maintaining its own version of the data, you lift the state up to their parent component.
function Parent() { const [sharedData, setSharedData] = React.useState(""); return ( <div> <InputComponent sharedData={sharedData} setSharedData={setSharedData} /> <DisplayComponent sharedData={sharedData} /> </div> ); } function InputComponent({ sharedData, setSharedData }) { return ( <input value={sharedData} onChange={(e) => setSharedData(e.target.value)} placeholder="Type something..." /> ); } function DisplayComponent({ sharedData }) { return <p>You typed: {sharedData}</p>; }
Here, Parent
holds the shared state (sharedData
) and passes it along with the updater function (setSharedData
) to its children. Both children now stay in sync without managing their own copies of the state.
In short:
Lifting State Up keeps your components coordinated and your data flow predictable.