简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM