React - Parent ↔ Child Communication
Overview
Estimated time: 15–25 minutes
Learn how to pass values down with props and update parent state from a child using callbacks.
Try it: Pick a Color
View source
const { useState } = React;
function ColorPicker({ value, onChange }){
return (
<select value={value} onChange={e => onChange(e.target.value)}>
<option>red</option>
<option>green</option>
<option>blue</option>
</select>
);
}
function App(){
const [color, setColor] = useState('red');
return (
<div>
<p>Selected: <strong>{color}</strong></p>
<ColorPicker value={color} onChange={setColor} />
</div>
);
}
ReactDOM.createRoot(document.getElementById('try-comm')).render(<App />);
Syntax primer
- Pass values down as props; pass callbacks up to update parent state.
- Prefer lifting state to the nearest common ancestor when siblings need the same data.
Common pitfalls
- Updating child state instead of lifting to parent when multiple children need the value.
Checks for Understanding
- When should you lift state up to a common parent?
- How do children communicate changes to parents?
Show answers
- When multiple components need to read or update the same data.
- By invoking callbacks passed from the parent via props.
Exercises
- Create a counter in the parent controlled by plus/minus buttons inside a child.
- Add validation in the parent and show error messages near the child input.
- Refactor to context when more than two levels need the same state.