Chapter 4 of 4
State in Practice
Sharing state between components and building a working counter.
Two sibling components cannot see each other's state. When both need the same value, move it up to their closest common parent. This is called lifting state up.
function Thermostat() {
const [temperature, setTemperature] = useState(20);
return (
<>
<Display value={temperature} />
<Slider value={temperature} onChange={setTemperature} />
</>
);
}
function Display({ value }) {
return <p>{value} degrees</p>;
}
function Slider({ value, onChange }) {
return (
<input
type="range"
value={value}
onChange={(event) => onChange(Number(event.target.value))}
/>
);
}Where should a piece of state live?
- Find every component that reads the value.
- Find their closest common parent.
- Put the state there, and pass the value and an updater down.
Write the counter update logic
Complete nextCount so it adds the step to the current value, but never goes below zero.
Build a working counter component
Wire the buttons so Add increases the count and Reset sets it back to 0. Use the updater form for Add.