DEV Community

Discussion on: You (probably) don't need that useState + useEffect

Collapse
 
townofdon profile image
Don Juan Javier • Edited

UPDATE - see follow up below.

Your concern is 100% warranted - useEffect dependencies are often the cause of infinite loop headaches, mainly from objects, arrays, and function expressions.

The set* functions returned from the useHook call reference the same functions between renders. Or, in other words:

[useState and useEffect] are guaranteed to have a stable signature between renders

The following as you pointed out would cause an infinite loop:

// object
const user = {};
useEffect(() => { /* ... */ }, [user]);

const dogs = [];
useEffect(() => { /* ... */ }, [dogs]);

const fetchSomethingCool = () => {};
useEffect(() => { /* ... */ }, [fetchSomethingCool]);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
townofdon profile image
Don Juan Javier

UPDATE - I think that React does some smart memoization for the dependencies, so my analysis is incorrect. The main thing that would cause a useEffect is performing a setState (the same as using one of the set* useState functions) inside of a useEffect, where the state value is part of the dependency array.

This is a good article that outlines some of the pitfalls and how to solve them: dmitripavlutin.com/react-useeffect...