How to lift state up in React

· Category: React

Short answer

Lifting state up means moving shared state from child components to their closest common parent, which then passes the state and callbacks down as props.

Steps

  1. Identify components that need the same changing data.
  2. Move the state to their closest common ancestor.
  3. Pass the current state down as props.
  4. Pass callback functions down so children can request state changes.

Example

function Parent() {
  const [celsius, setCelsius] = useState(0);

  return (
    <>
      <TemperatureInput scale="c" value={celsius} onChange={setCelsius} />
      <TemperatureInput scale="f" value={toF(celsius)} onChange={(f) => setCelsius(toC(f))} />
    </>
  );
}

function TemperatureInput({ scale, value, onChange }) {
  return (
    <input
      value={value}
      onChange={(e) => onChange(Number(e.target.value))}
    />
  );
}

Tips

  • Only lift state that is genuinely shared. Local state should stay local.
  • If many components need the same state, consider Context or a dedicated state management library.