State LiftingAdvanced
1Question 1 of 1
javascriptWhat is 'Lifting State Up' and when should it be applied in React?
Explanation & Concept
Lifting State Up is the pattern of moving shared state to the closest common ancestor of two or more components that need to share that state.
The parent passes the state down as props, and passes callback functions allowing children to request state updates.
Code Example
javascript
import { useState } from "react";
function TemperatureInput({ scale, temperature, onTemperatureChange }) {
return (
<div>
<label>Enter temperature in {scale}:</label>
<input value={temperature} onChange={(e) => onTemperatureChange(e.target.value)} />
</div>
);
}
export function Calculator() {
const [temp, setTemp] = useState("");
return (
<div>
<TemperatureInput scale="Celsius" temperature={temp} onTemperatureChange={setTemp} />
<TemperatureInput scale="Fahrenheit" temperature={temp} onTemperatureChange={setTemp} />
</div>
);
}How It Works & Key Takeaways
By lifting `temp` to `Calculator`, both inputs stay synchronized without duplicate state or complex syncing events.
Mock Test · 1 Questions · Optional
Ready for Higher-Order Components?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions