0

I have a simple React function component and noticed some strange behavior while trying to use hooks. It persists even after commenting out all content of the function so I don't think it has anything to do with changing state or props.

this code:

let renderNum = 0;

export default function MyComponent(props: any) {
  console.dir(props)
  renderNum += 1;
  console.log('renderNum ' + renderNum)

  return (
    <>
      <h1>renderNum {renderNum}</h1>
    </>
  )
};

results in the following behavior: prtScr

  1. the counter starts at 0
  2. there's a console.dir(props)
  3. the counter is incremented by 1
  4. there's another console.dir(props) <--- 2nd reder!?
  5. the view displays renderNum 2

How is this possible?

Why is the counter incremented twice?

And even so - why is there no second log of the counter?

How can the console.dir() be executed twice but not console.log()?

notes:

  • the props never change (empty list)
  • tried disabling all other code, including all other components in parent
  • removed all uses of context or redux stuff
  • tried alternative ordering of logging and incrementing
  • I'm a newbie with React and might miss some basic fact
  • this is relevant to me because I'm trying to add dynamic RTK listeners and need to add it inside this component; otherwise cannot use hooks

finally:

If this is expected behavior (), how else can I add a listener to a redux-toolkit action that does not alter any store value? I'd post this a separate question but not sure how to formulate it properly.

  • 1
    https://reactjs.org/docs/strict-mode.html – Brian Thompson Mar 01 '22 at 21:53
  • Thanks for the link. I saw it but overlooked it. Indeed, removing the strictMode tag prevents 2nd render. I find this very strange but have much to read for now. Post an answer if you'd like me to accept and close. – rmrfxyz Mar 01 '22 at 23:21
  • The duplicate link will be more helpful to future visitors than me posting another answer. It is strange, but if you dive deeper into how `useEffects` and `useState` work, and how stale closures/etc can be issues, it makes a lot of sense why double renders would help reduce bugs – Brian Thompson Mar 02 '22 at 02:41

0 Answers0