Reputation: 7324
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?
Upvotes: 8
Views: 6046
Reputation: 31365
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
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
.
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.
Upvotes: 7