Fullstack CourseLearn by building

react · source-driven

Sharing data between components

When two children need the same data, lift state to their closest shared parent and pass it down as props — “lifting state up”.

You will learn

  • How props pass data parent → child
  • How to lift state to a common parent
  • How children notify parents via callback props

Lift state up

From the docs: move state out of the children into the parent that contains them. Pass the value and the event handler down as props.

export default function MyApp() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <MyButton count={count} onClick={handleClick} />
      <MyButton count={count} onClick={handleClick} />
    </div>
  );
}

function MyButton({ count, onClick }) {
  return (
    <button onClick={onClick}>
      Clicked {count} times
    </button>
  );
}

Counters that update together

Recap

  • Props are read-only inputs from the parent
  • Shared state lives in the closest common parent
  • Children call callbacks (onClick) to request updates
  • This is one-way data flow

Challenge

Try this

Add a Reset button in the parent that sets count back to 0. Children should not own that logic.