admin管理员组

文章数量:1336311

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?

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?

Share Improve this question edited May 1, 2020 at 15:11 Patrick Roberts 52k10 gold badges117 silver badges163 bronze badges asked May 1, 2020 at 13:16 TheNormalPersonTheNormalPerson 5915 silver badges18 bronze badges 3
  • 4 This is done on purpose in development mode. – Patrick Roberts Commented May 1, 2020 at 13:22
  • @PatrickRoberts, oh i see, so... how do i avoid it? – TheNormalPerson Commented May 1, 2020 at 14:16
  • You don't. In production mode it won't do that, and in development mode, it's done to quickly reveal issues if you perform mutations or store state externally to react hooks. In short, nothing's wrong and nothing needs to be fixed. – Patrick Roberts Commented May 1, 2020 at 15:02
Add a ment  | 

1 Answer 1

Reset to default 10

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 mon antipatterns, including state mutations and externally managed state.

These efforts are in preparation for the uping 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 plex.

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.

本文标签: javascriptAny reason for a react state hook set callback to fire twiceStack Overflow