javascript - Any reason for a react state hook set callback to fire twice? - Stack Overflow

I have this simple code:const [state, setState] = useState([]);useEffect(() => {socket.on('some

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742336136a4424688.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信