TExcelTAD
Home › React › React Lifting State Up

React Lifting State Up

Sometimes two components need to share the same changing data. Because state belongs to one component and data flows down through props, the solution is to lift the state up: move it to the closest common parent, then pass the value and a function to change it down to the children.

The problem: two separate states

Here two accordion panels each keep their own isOpen state. We want only one panel open at a time, but neither panel knows about the other:

jsx · try it yourself
import { useState } from 'react';

function Panel({ title, children }) {
  const [isOpen, setIsOpen] = useState(false);
  return (
    <section style={{ border: '1px solid #ccc', borderRadius: 6, padding: 10, marginBottom: 8, width: 320 }}>
      <h3 style={{ margin: 0 }}>{title}</h3>
      {isOpen ? <p>{children}</p> : <button onClick={() => setIsOpen(true)}>Show</button>}
    </section>
  );
}

export default function App() {
  return (
    <div>
      <Panel title="Shipping">Orders ship within 2 business days.</Panel>
      <Panel title="Returns">Return any item within 30 days for a full refund.</Panel>
    </div>
  );
}

Both panels can be open together. To coordinate them, the decision must live above them.

The solution: state in the parent

Three steps:

  1. Remove the state from the child and make the value a prop (isActive).
  2. Add the state to the common parent (activeIndex).
  3. Pass the value and an event handler (onShow) down.
jsx · try it yourself
import { useState } from 'react';

function Panel({ title, children, isActive, onShow }) {
  return (
    <section style={{ border: '1px solid #ccc', borderRadius: 6, padding: 10, marginBottom: 8, width: 320 }}>
      <h3 style={{ margin: 0 }}>{title}</h3>
      {isActive ? <p>{children}</p> : <button onClick={onShow}>Show</button>}
    </section>
  );
}

export default function App() {
  const [activeIndex, setActiveIndex] = useState(0);
  return (
    <div>
      <Panel title="Shipping" isActive={activeIndex === 0} onShow={() => setActiveIndex(0)}>
        Orders ship within 2 business days.
      </Panel>
      <Panel title="Returns" isActive={activeIndex === 1} onShow={() => setActiveIndex(1)}>
        Return any item within 30 days for a full refund.
      </Panel>
      <Panel title="Warranty" isActive={activeIndex === 2} onShow={() => setActiveIndex(2)}>
        All electronics include a two-year warranty.
      </Panel>
    </div>
  );
}

Now Panel is a controlled component: the parent decides what it shows. The panels became simpler too — they just display props and report clicks.

Sharing input between siblings

A classic example: two inputs that show the same quantity in different units. Each input displays a value derived from one piece of state in the parent:

jsx · try it yourself
import { useState } from 'react';

function LengthInput({ label, value, onChange }) {
  return (
    <label style={{ display: 'block', marginBottom: 8 }}>
      {label}:{' '}
      <input type="number" value={value} onChange={(e) => onChange(e.target.value)} style={{ width: 120 }} />
    </label>
  );
}

const round = (n) => Math.round(n * 1000) / 1000;

export default function App() {
  const [cm, setCm] = useState(100);

  return (
    <div>
      <LengthInput label="Centimetres" value={cm} onChange={(v) => setCm(Number(v))} />
      <LengthInput label="Inches" value={round(cm / 2.54)} onChange={(v) => setCm(round(Number(v) * 2.54))} />
      <LengthInput label="Feet" value={round(cm / 30.48)} onChange={(v) => setCm(round(Number(v) * 30.48))} />
      <p>{cm >= 180 ? 'That is tall! 🦒' : 'Keep going…'}</p>
    </div>
  );
}

We store only centimetres. Inches and feet are derived while rendering, so the values can never disagree.

Single source of truth

Every piece of changing data should have exactly one owner — the component that holds it in state. Other components receive it as props. Ask these questions to find the owner:

Question Answer →
Which components display this data? list them
What is their closest common ancestor? that's the owner candidate
Can the value be computed from other state or props? then it's not state at all — derive it

A shopping cart example

The product list adds items, and the summary shows totals. Both need the cart, so the cart lives in App:

jsx · try it yourself
import { useState } from 'react';

const PRODUCTS = [
  { id: 1, name: 'Green tea', price: 4 },
  { id: 2, name: 'Croissant', price: 3 },
  { id: 3, name: 'Smoothie', price: 6 },
];

function ProductList({ onAdd }) {
  return (
    <ul>
      {PRODUCTS.map((p) => (
        <li key={p.id}>
          {p.name} (${p.price}) <button onClick={() => onAdd(p)}>Add</button>
        </li>
      ))}
    </ul>
  );
}

function CartSummary({ cart, onClear }) {
  const count = cart.reduce((n, item) => n + item.qty, 0);
  const total = cart.reduce((sum, item) => sum + item.qty * item.price, 0);
  return (
    <div style={{ background: '#f6f8fa', padding: 10, borderRadius: 6 }}>
      🛒 {count} item(s) — <strong>${total}</strong>
      {cart.map((item) => <div key={item.id}>{item.qty} × {item.name}</div>)}
      {count > 0 && <button onClick={onClear}>Clear</button>}
    </div>
  );
}

export default function App() {
  const [cart, setCart] = useState([]);

  function addToCart(product) {
    const existing = cart.find((item) => item.id === product.id);
    if (existing) {
      setCart(cart.map((item) => (item.id === product.id ? { ...item, qty: item.qty + 1 } : item)));
    } else {
      setCart([...cart, { ...product, qty: 1 }]);
    }
  }

  return (
    <div style={{ display: 'flex', gap: 24 }}>
      <ProductList onAdd={addToCart} />
      <CartSummary cart={cart} onClear={() => setCart([])} />
    </div>
  );
}

Tip: Lift state only as high as needed. If state is lifted too far up, many components re-render for no reason and props have to pass through layers that don't care. For data needed everywhere (theme, current user), the useContext lesson shows a better tool.

Test yourself

Two sibling components need the same changing value. Where should its state live?

  1. In both siblings, kept in sync with effects
  2. In their closest common parent
  3. In a global variable
  4. In the sibling that renders first

How does a child change state that lives in its parent?

  1. By modifying its props
  2. By calling a function the parent passed as a prop
  3. By calling the parent's useState
  4. It can't

In the length converter, why are inches not stored in state?

  1. Numbers can't be stored in state
  2. Inches can be derived from centimetres, so storing them would duplicate data
  3. State can only hold one value per app
  4. Inputs can't be controlled