State and Event HandlingLesson 2.4
Lifting state up in React component trees
shared state problem, lifting state pattern, passing callbacks as props, sibling communication, single source of truth, when to lift state
Lifting State Up
When two sibling components need to share the same data, move the state up to their closest common parent. The parent owns the state and passes it down via props. This is called 'lifting state up.'
The Problem
// TemperatureA and TemperatureB need the same value
// If each has its own state, they go out of syncThe Solution
import { useState } from 'react';
function TemperatureInput({ value, onChange, unit }) {
return (
<div>
<label>{unit}: </label>
<input
value={value}
onChange={e => onChange(e.target.value)}
/>
</div>
);
}
function Calculator() {
const [celsius, setCelsius] = useState('');
const fahrenheit = celsius ? (celsius * 9/5 + 32).toFixed(1) : '';
return (
<div>
<TemperatureInput
value={celsius}
onChange={setCelsius}
unit="Celsius"
/>
<p>Fahrenheit: {fahrenheit}</p>
</div>
);
}The parent (Calculator) is the single source of truth. The child calls onChange โ a callback from the parent โ to update state. Data flows down, events flow up. This pattern scales to larger trees without a state manager.
