Documentation defines usePrevious without a dependency array, why?

Viewed 272

This is a copy-n-paste from: Hooks FAQ usePrevious

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });  // no dependency arg, why?
  return ref.current;
}

Since useEffect is called without a dependency array, its function argument will be called for every render. Is it safe to limit this to only when value changes by adding value to the useEffect dependency array, like this:

  useEffect(() => {
    ref.current = value;
  }, [value]);

I'm wondering if there is some scenario where ref.current must updated every render, which would explain the omission of [value] from the documentation.

1 Answers

In this example, "every render" basically means whenever the value variable changes anyway since there is only one useState hook. So adding value to the deps array would make no difference in this case. Omitting it doesn't make a difference either since it's never being run with the same values (only after a change to count in the parent function).

If there was another useState somewhere which was causing another re-render, then yeah adding value to the deps array would cut down on ref.current updates.

Related