Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint exhaustive-deps: ignore value that came from a ref

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?

like image 345
CALICAWESOME Avatar asked Aug 30 '25 16:08

CALICAWESOME


1 Answers

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])
like image 159
CertainPerformance Avatar answered Sep 02 '25 07:09

CertainPerformance