Skip to content
Advertisement

What’s the best way to avoid react-hooks/exhaustive-deps?

I currently use the useEffect hook to run some function or update a variable as an effect of another value/variable being changed

example:

 useEffect(() => {
   setValues(types[formStep]]);
 }, [formStep]);

I am using the above code to update a variable after another variable has changed, however i keep getting the warning that
React Hook useEffect has a missing dependency 'types

and obviosuly when i include ‘types’ as a dependency, the application falls into a loop and i get the following error

Maximum update depth exceeded.

What is the best way to achieve the variable update but avoid the error? not just for this example for for all cases where you need to update a variable depending on another variable changing before it.

Advertisement

Answer

Some solutions found here: https://www.benmvp.com/blog/object-array-dependencies-react-useEffect-hook/.

Another option could be to stringify the dependency so that it is not treated as a different object everytime.

useEffect(() => {}, [JSON.stringify(data)])
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement