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

  1. When should you lift state up to a common parent?
  2. How do children communicate changes to parents?
Show answers
  1. When multiple components need to read or update the same data.
  2. By invoking callbacks passed from the parent via props.

Exercises

  1. Create a counter in the parent controlled by plus/minus buttons inside a child.
  2. Add validation in the parent and show error messages near the child input.
  3. Refactor to context when more than two levels need the same state.