Sikau

React · Day 10 · about 30 min

Sharing state between components

Lift state up to the closest common parent.

Two components, one truth

A product list adds items; a header shows the cart count. They need the *same* data. The React way: lift the state up to their common parent, pass the value down as props, and pass functions down so children can ask for changes.

Data down, events up

import { useState } from "react";

function Header({ count }) {
  return <h2>🛒 {count} in cart</h2>;
}

function Product({ name, onAdd }) {
  return (
    <p>
      {name} <button onClick={onAdd}>Add</button>
    </p>
  );
}

export default function Shop() {
  const [cart, setCart] = useState([]);
  const add = (name) => setCart((c) => [...c, name]);

  return (
    <div>
      <Header count={cart.length} />
      <Product name="Momo" onAdd={() => add("Momo")} />
      <Product name="Lassi" onAdd={() => add("Lassi")} />
    </div>
  );
}
  • Keep state as low as possible, but as high as necessary.
  • Never copy the same data into two components' state — they'll drift apart.
  • Name callback props onSomething; name the handlers handleSomething.

The rest of this lesson

  • Finding where state belongsexplain
  • Not too high, not too lowexplain
  • Who owns the state?predict
  • One click, end to endorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React