Strive for a minimum required state in a React component

smlka

Andrey Smolko

Posted on August 27, 2022

Strive for a minimum required state in a React component

Keep a component state as minimal as possible and avoid unnecessary state synchronization .

🚫 Before refactoring - b is a redundant state which should be sync:

export default function App() {
  const [a, setA] = useState(1);
  const [b, setB] = useState(1);

  function updateA(x) {
    setA(x);
  };

  function updateB() {
    setB(1 + a);
  };

  useEffect(() => {
    updateB()
  },[a])


  return (
    <div>
      <button onClick={() => updateA(a+1)}>Click</button>
        <p>a: {a}</p>
        <p>b: {b}</p>
    </div>
)
};
Enter fullscreen mode Exit fullscreen mode

✅ After refactoring - a is a minimum sufficient state and just derive b from it:

export default function App() {
  const [a, setA] = useState(1);

  function updateA(x) {
    setA(x);
  };

  function updateB() {
    return a+1
  };

  return (
    <div>
      <button onClick={() => updateA(a+1)}>Click</button>
      <p>a: {a}</p>
      <p>b: {updateB()}</p>
    </div>
  )
};
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
smlka
Andrey Smolko

Posted on August 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related