Infinite loop in useEffect using blank object or array
See original GitHub issueUsing React Version: 16.8.4 When using blank object or array as a setter for function inside useEffect does cause infinite loop. However using string or number does not trigger this. Here’s the minimal example:
function Example() {
const [count, setCount] = useState(0);
const [foo, setFoo] = useState({});
useEffect(() => {
console.log("Infinite Loop");
setCount(100); // doesn't cause infinite loop.
// but this does
// setFoo({}); // or setFoo([]);
});
return <div />;
}
I don’t know if it’s a bug or default behaviour because in earlier version of react (in v16.7.0-alpha.0), both string and number also causing infinite loop which seems to be fixed in latest one.
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (2 by maintainers)
Top Results From Across the Web
Infinite loop in useEffect - reactjs - Stack Overflow
An empty array at the end of a useEffect is a purposeful implementation by the developers to stop infinite loops in situations where...
Read more >How to solve the React useEffect Hook's infinite loop patterns
To get rid of your infinite loop, simply use an empty dependency array like so: const [count, setCount] = useState ...
Read more >5 useEffect Infinite Loop Patterns | by Naveen DA
useEffect uses shallow object comparison to determine, whether the data was changed or not. Due to weird JavaScript conditional systems ....
Read more >How to Solve the Infinite Loop of React.useEffect()
1.1 Fixing dependencies ... The infinite loop is fixed by correct management of the useEffect(callback, dependencies) dependencies argument.
Read more >React useEffect infinite loop despite empty array-Reactjs
Related Query · React useEffect infinite loop despite empty array · React Redux state array variable pass as prop to child component, either...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
It seems to behave according to the docs.
Both
{}
and[]
creates a new object or array and hence triggers an update.100
is primitive and doesn’t.Re: example in https://github.com/facebook/react/issues/15096#issuecomment-472349151, you can fix it by adding the dependencies argument. (In this case, it’s
[]
because your effect doesn’t depend on any values from render scope exceptsetCurrentUser
which is guaranteed to be stable.)Note that you should only do it when it’s safe — i.e. when you don’t use any props/state and values derived from them in the effect, and you also don’t call any functions that use those.
See:
Hope this helps.
For a deeper dive: