Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should refs be in listed as dependencies for useEffect and such?

As I understand, the containers returned by useRef are always the same - yet referencing them in useEffect and similar functions results in eslint exhaustive-deps warning. Is it safe to ignore the warning in this case, and what's a good way to avoid both clogging the output log with warnings, and my code with disable-line comments? Or should I just stick them into dependency list to keep eslint happy?

like image 586
riv Avatar asked Oct 16 '22 01:10

riv


1 Answers

When useRef is first called it creates an object with a current property. This object will remain the same across subsequent renders. Ie: the reference to this object won't change.

https://reactjs.org/docs/hooks-reference.html#useref

enter image description here

So it's safe to omit it from the dependencies array.

See the code below (also available in the Sandbox link):

https://codesandbox.io/s/cocky-dhawan-ys267?file=/src/App.js

const someRef = useRef({foo: "bar"});
let x = 1;

useEffect(() => {
  console.log(someRef.current.foo);
  console.log(x);
}, []);              // THERE IS A WARNING HERE FOR THE "x"

eslint/exhaustive-deps is only worrying about the x, and not the someRef.current.foo.

enter image description here

NOTE: I've just put the x there to make sure the warnings were being triggered by eslint.

The reason behind this is that useRef isnot related to the render cycle. I mean, it's not recreated, neither is automatically updated after every render, like state, props or variables created during render usually are.

Are you sure you are getting this warning for useRef? See the CodeSandbox link and give it a double check. Check how are you referencing them into the useEffect and also check your React and Eslint/plugin versions.

like image 93
cbdeveloper Avatar answered Nov 03 '22 21:11

cbdeveloper