Clean β’ Professional
In React, βLifting State Upβ is a core concept that allows multiple components to share and synchronize the same data. Instead of keeping state separately in child components, you βliftβ it up to their nearest common parent so it can be passed down as props.
This approach helps maintain a single source of truth and ensures that all components using that data remain in sync.
When two or more components need access to the same data, keeping the state in one of them can cause inconsistencies.
Instead, you can βliftβ that state up to a parent component, which then manages the state and passes it down to children as props.
Lifting state up helps to:
Letβs say you have two components:
Each of these needs the same temperature value β so we lift the state to a common parent.
Example Code:
import React, { useState } from "react";
// Child Component: Temperature Input
function TemperatureInput({ scale, temperature, onTemperatureChange }) {
return (
<fieldset>
<legend>Enter temperature in {scale === "c" ? "Celsius" : "Fahrenheit"}:</legend>
<inputvalue={temperature}
onChange={(e) => onTemperatureChange(e.target.value)}
/>
</fieldset>
);
}
// Child Component: Boiling Verdict
function BoilingVerdict({ celsius }) {
return (
<p>
{celsius >= 100 ? "The water would boil." : "The water would not boil."}
</p>
);
}
// Parent Component: Manages shared state
function Calculator() {
const [temperature, setTemperature] = useState("");
return (
<div>
<TemperatureInputscale="c"
temperature={temperature}
onTemperatureChange={setTemperature}
/>
<BoilingVerdict celsius={parseFloat(temperature)} />
</div>
);
}
export default Calculator;
Single Source of Truth
Keep the shared state in one place to avoid inconsistencies.
Data Flows Down, Events Flow Up
Controlled Components
Children become βcontrolledβ by their parent β they rely entirely on props for their values.
You should lift state up when:
Avoid lifting state up when: