0

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

Related questions I looked at:

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;
Simon Crane
  • 2,122
  • 2
  • 10
  • 21
weiya ou
  • 2,730
  • 1
  • 16
  • 24

1 Answers1

0

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;
Oussama
  • 36
  • 1
  • 3