admin管理员组文章数量:1323698
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 badges1 Answer
Reset to default 7When 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
版权声明:本文标题:javascript - Should refs be in listed as dependencies for useEffect and such? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742132858a2422239.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论