Home > Blockchain >  useRef passed in as parameter needs to be added to dependencies?
useRef passed in as parameter needs to be added to dependencies?

Time:03-02

From the following two questions, I understand that useRef does not need to add update dependencies.

https://stackoverflow.com/a/60476525/9854149

https://stackoverflow.com/a/63353582/9854149

But when useRef is used as props, eslint always warns about hook missing dependencies?

import { useCallback, useEffect, useRef } from 'react';

const One = ({ refEl }) => {
  const clickHandler = useCallback(e => {
    refEl.current = 1111;
  }, []); //⚠️ React Hook useCallback has a missing dependency: 'refEl'. Either include it or remove the dependency array.

  useEffect(() => {
    refEl.current = 2222;
  }, []); //⚠️ React Hook useCallback has a missing dependency: 'refEl'. Either include it or remove the dependency array.

  return (
    <div onClick={clickHandler} ref={refEl}>
      One
    </div>
  );
};

function App() {
  const el = useRef('');
  return <One refEl={el} />;
}

export default App;

CodePudding user response:

You should add all values that are used in the effect to the dependency array, even if you think that their values do not change (because it may not be obvious). This makes sure that the component is re-rendered whenever the values passed from the parent component update.

For example (and this is just an example), it could be that the One component is rendered before the el variable has been assigned a value because useRef() works asynchronously.

Read the note at the end of this section: https://reactjs.org/docs/hooks-effect.html#explanation-why-effects-run-on-each-update

CodePudding user response:

eslint can't tell that refEl is a ref so it will just consider it as an ordinary prop to pass a ref down to a functional component you should use React.forwardRef

import { useCallback, useEffect, useRef, forwardRef } from "react";

const One = forwardRef((props, ref) => {
  const clickHandler = useCallback((e) => {
    ref.current = 1111;
  }, [ref]);

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

  return (
    <div onClick={clickHandler} ref={ref}>
      One
    </div>
  );
});

function App() {
  const el = useRef("");
  return <One ref={el} />;
}

export default App;
  • Related