Careeroza
Lifting State Up and Siblings
Sharing State Between Siblings
Example
Two siblings cannot talk directly. Move ("lift") the shared state to their closest common parent and pass it down to both.
import { useState } from 'react';
function CelsiusInput({ celsius, onChange }) {
return <p>°C <input type="number" value={celsius} onChange={(e) => onChange(e.target.value)} /></p>;
}
function FahrenheitView({ celsius }) {
const f = celsius === '' ? '' : (Number(celsius) * 9) / 5 + 32;
return <p>°F <b>{f}</b></p>;
}
export default function App() {
const [celsius, setCelsius] = useState('25');
return (
<div>
<CelsiusInput celsius={celsius} onChange={setCelsius} />
<FahrenheitView celsius={celsius} />
</div>
);
}Result
Summary
| Direction | How |
|---|---|
| Parent → child | props |
| Child → parent | callback function prop |
| Sibling ↔ sibling | lift state to the common parent |
| Far-away components | Context API or Redux (see Props Drilling) |