I have a utility function to store an ever-changing value in a ref:
export function useRefOf<T>(value: T) {
const ref = useRef(value);
useEffect(() => {
ref.current = value;
}, [value]);
return ref;
}
However, when I use this in an effect that I don't want to re-render on the changing of a value:
const someValueRef = useRefOf(someValue);
useEffect(() => {
doSomeGreatStuff(someValueRef.current);
}, [doSomeGreatStuff])
I break the ESLint exhaustive-deps
rule:
React Hook useEffect has a missing dependency: 'someValueRef'. Either include it or remove the dependency array
I know that if I used a regular useRef
instead of my useRefOf
though, ESLint wouldn't complain.
How can I tell ESLint to treat useRefOf
like a ref from useRef
and tolerate it not being in dependency arrays?
Often, with exhaustive-deps
, the "clean" way to solve the problem without ignoring the rule is to add the value to the dependency array, even if doing so doesn't actually accomplish anything. That approach can be used here. A ref is stable; the value returned by a given component's useRef
will be the same object every time. So, your code will perform identically to what it's doing now if you change
}, [doSomeGreatStuff])
to
}, [doSomeGreatStuff, someValueRef])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With