admin管理员组

文章数量:1323519

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 ments? Or should I just stick them into dependency list to keep eslint happy?

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 ments? Or should I just stick them into dependency list to keep eslint happy?

Share Improve this question asked Aug 10, 2020 at 18:38 rivriv 7,3533 gold badges41 silver badges74 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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/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.

本文标签: javascriptShould refs be in listed as dependencies for useEffect and suchStack Overflow