I've placed debuggers in the render of a ponent and see that it gets ran twice sometimes, if not most of the time. Is it because the first render is before the ponent receives any props? And the 2nd time is when it receives it? I thought ponents go through the lifestyle of mounting, receiving props, and then rendering? Or does it mount, render, check props, and then re-render?
I've placed debuggers in the render of a ponent and see that it gets ran twice sometimes, if not most of the time. Is it because the first render is before the ponent receives any props? And the 2nd time is when it receives it? I thought ponents go through the lifestyle of mounting, receiving props, and then rendering? Or does it mount, render, check props, and then re-render?
Share Improve this question asked Jun 19, 2017 at 18:46 stackjleistackjlei 10k19 gold badges73 silver badges124 bronze badges 2- 1 without code we can only guess, my guess is that you're changing the ponent's state triggering rerenders – niceman Commented Jun 19, 2017 at 18:54
-
another guess is that your
shouldComponentUpdate
is flawed – niceman Commented Jun 19, 2017 at 18:55
2 Answers
Reset to default 7Components do not re-render if they have initial props. The only reason that it would re-render is if it is receiving props after the initial render, or if you are changing state.
In my previous question, I had an issue, and I quote:
" ...I know that most of these features (and possibly more) are available in function ponents (introduced most by hooks), but they do not work as I intend them too, because they are NOT exactly the same, like
useEffect(() => {code}, [])
is known to replaceponentDidMount()
, an yet upon mount it renders twice in any app I develop, passing false data... "
To that issue, CertainPerformance replied:
" ...Sounds like you have strict mode enabled and are performing operations with side-effects, which should be avoided. You probably just need to figure out the right way to structure the code with functional ponents - nearly anything you'd want to do can be done reasonably elegantly in functional ponents, though not absolutely everything... "
Which lead me to research a little and find this interesting answer:
It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for ponents with Hooks because those are more likely to accidentally have side effects in the wrong place.
You can read more about that on GitHub.