SmartCodingTips

πŸ“€ Lifting State Up

When multiple components need to share and synchronize state, it’s often best to **move the state up** to their closest common ancestor β€” a pattern known as Lifting State Up.


🎯 Why Lift State?

  • Coordinate data between sibling components
  • Keep a single source of truth
  • Make data flow predictable and easier to debug

πŸ“¦ Example Scenario

Imagine two components: one updates a value, and the other displays it. Instead of storing state in both, you lift it up to a parent.

// Parent Component
function Parent() {
  const [count, setCount] = React.useState(0);
  return (
    <>
      <Counter value={count} />
      <Increment onClick={() => setCount(count + 1)} />
    </>
  );
}

function Counter({ value }) {
  return <p>Count: {value}</p>;
}

function Increment({ onClick }) {
  return <button onClick={onClick}>+1</button>;
}

βœ… Benefits

  • Ensures consistent state across components
  • Improves control and maintainability
  • Makes debugging easier with a single source of truth

πŸ“‹ Summary

  • Shared state should live in the nearest common parent
  • Child components communicate via props and callbacks
  • Lifting state up helps avoid data duplication