react icon indicating copy to clipboard operation
react copied to clipboard

Bug: Infinite rendering resulting in freezing of tab/browser

Open palerdot opened this issue 3 years ago • 5 comments

React is not preventing infinite rendering/looping and results in freezing of browser.

The root cause of this issue is because the dependency array of useEffect compares object/array by reference. But, this is a serious issue because

  • This is a common trap people might get into because of dynamic nature of Javascript, and people might not know the thing they are passing to dependency array is a primitive value or an array/object.
  • React should catch this infinite rendering and throw a helpful error. This error is already thrown by React for some of the cases. But, clearly React does not catch this for all the cases.
  • The documentation of useEffect does not have a single reference to this gotcha - guarding against passing object/array to the dependency array, since reference of the object/array is being checked, not a deep comparison value. Some solutions already exist like https://github.com/kentcdodds/use-deep-compare-effect, https://stackoverflow.com/questions/54095994/react-useeffect-comparing-objects/63965274#63965274. But, only people who are aware of this behaviour of useEffect will reach out to these solutions (or they might manually deep compare with their own custom hook as some people do in the linked stackoverflow link)

It would also be helpful if useEffect includes a helpful option like

useEffect(() => {
 // myArray, myObject gets new reference on evey render
}, [myArray, myObject], {
   deepCompare: true/false // it would be helpful to have this instead of reaching for custom hooks/npm packages
})

React version: 16.12.x (any latest version)

Steps To Reproduce

  1. Click the codesandbox link - https://codesandbox.io/s/apollo-client-uselazyquery-example-forked-kmc1u?file=/src/App.js.
  2. Click Topics link and then select Countries link.

Warning: Please be aware that tab/browser will freeze. It is better to open the console before hand, so that you can see the looping from console logs.

Link to code example:

CodeSandbox reproduction

Current behavior:

  • React does not prevent infinite loop/rendering. Browser tab freezes, and the end user has no idea that the tab has freezed. They have to force quit the tab.

Expected behavior:

  • React should give a helpful warning that an infinite render/loop is going on.
  • React should pinpoint the exact issue - the array/object passed to useEffect dependency is triggering infinite rendering

palerdot avatar Oct 09 '20 15:10 palerdot

Why no one care about this ? I've a lot of problems with this. What a terriable DX

dungtran5 avatar Jul 15 '22 05:07 dungtran5

yep, this would be a useful to prevent crash of entire browser

shahul01 avatar Aug 27 '23 14:08 shahul01