Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason for a react state hook set callback to fire twice?

I have this simple code:

const [state, setState] = useState([]);

useEffect(() => {
  socket.on('something', data => {
    console.log('ONE');

    setState(old => {
      console.log('TWO');

      const newArr = [...old];

      // do something to newArr
      return newArr;
    });
  });

  return () => {
    socket.off('something');
  };
}, []);

Everything works as intended but for some reason the something callback triggers once (the ONE is printed once), but inside when I set the state, the setState callback is called twice (it prints TWO twice). Why is that?

like image 329
TheNormalPerson Avatar asked Mar 02 '23 12:03

TheNormalPerson


1 Answers

This is a feature of React's strict mode (no, it's not a bug).

The setState() updater function, among other methods, is invoked twice in a strict context during development mode only in order to quickly reveal common antipatterns, including state mutations and externally managed state.

These efforts are in preparation for the upcoming concurrent mode, which is expected to regularly invoke these methods multiple times per render as the internal implementation of react's render phase grows more complex.

In short, nothing needs to be fixed. React is just making it easier for you to discover logic errors in development while staying performant in production.

like image 74
Patrick Roberts Avatar answered Mar 31 '23 13:03

Patrick Roberts