Share state between components

19.3

Put shared state in the closest common parent and pass values and event handlers to the children.

On this page

Give each value one owner

Two components that show the same selection should read the same state. If every child keeps its own copy, the values can drift apart. Store the selected ID in the parent and derive the selected item while rendering.

import { useState } from "react";

function Choice({ label, selected, onChoose }) {
  return <button aria-pressed={selected} onClick={onChoose}>{label}</button>;
}

export default function ProductPicker() {
  const [product, setProduct] = useState("pen");
  return (
    <>
      <Choice label="Pen" selected={product === "pen"} onChoose={() => setProduct("pen")} />
      <Choice label="Notebook" selected={product === "notebook"} onChoose={() => setProduct("notebook")} />
      <p>Selected: {product}</p>
    </>
  );
}

Keep children reusable

A controlled child gets its current value from props and asks the parent to change it through a callback. Local state is still useful for things only one child cares about.

import { useState } from "react";

function QuantityInput({ value, onChange }) {
  return (
    <label>
      Quantity
      <input type="number" min="1" value={value}
        onChange={event => onChange(event.target.value)} />
    </label>
  );
}

export default function OrderForm() {
  const [quantity, setQuantity] = useState("1");
  return <QuantityInput value={quantity} onChange={setQuantity} />;
}

Official references