0

I am trying to understand why using the previous state to update the state of an element in React is preferred over using the current state. I have seen this practice being used in various code examples and tutorials, but I couldn't find a satisfying example that clearly explains the reasoning behind it.

I understand that updating the state using the previous state ensures that the correct state is used for the update and avoids race conditions, but I am still not clear on the details.

Can someone please provide a clear and concise explanation, along with a simple code example that demonstrates the difference between updating the state using the current state vs the previous state? I would appreciate any resources or references that can help me understand this better. Thank you.

Kalyan cs
  • 1
  • 1

1 Answers1

0

This is broken (shows 0 and then 1 forever):

import { useEffect, useState } from "react";

export default function App() {
  const [value, setValue] = useState(0);

  useEffect(() => {
    const int = setInterval(() => {
      // value is always 0 here because of stale closure
      setValue(value + 1);
    }, 1000);
    return () => clearInterval(int);
  }, []);

  return <div>{value}</div>;
}

Live example

This works fine (adds 1 to the state each second):

import { useEffect, useState } from "react";

export default function App() {
  const [value, setValue] = useState(0);

  useEffect(() => {
    const int = setInterval(() => {
      // value is different every time
      setValue((value) => value + 1);
    }, 1000);
    return () => clearInterval(int);
  }, []);

  return <div>{value}</div>;
}

Live example

Konrad
  • 21,590
  • 4
  • 28
  • 64