react icon indicating copy to clipboard operation
react copied to clipboard

eslint-plugin-react-hooks should flag uses of createRef in function components

Open danvk opened this issue 5 years ago • 3 comments

Using createRef in a function component is almost certainly a mistake. You probably want useRef instead. This can easily lead to confusing bugs. See, for example, this popular Stack Overflow question.

Banning createRef outright would yield false positives on class components. I suggested adding a rule to flag this specifically in function components to eslint-plugin-react (https://github.com/yannickcr/eslint-plugin-react/issues/2966) but they suggested that I file an issue over here instead.

React version: [email protected]

Steps To Reproduce

  1. Set up eslint-plugin-react-hooks and create a function component that uses React.createRef.
  2. No complaints.

Link to code example: https://codesandbox.io/s/cool-volhard-9zj0s

export default function App() {
  const ref = React.createRef(0);
  // Change to this to make the example work as intended:
  // const ref = React.useRef(0);
  const [, update] = React.useState(0);

  const handleClick = () => {
    ref.current += 1;
    update((n) => n + 1);
  };
  React.useEffect(() => {
    ref.current = 0;
  }, [ref]);

  return (
    <div className="App" ref={ref}>
      <h1>Hello CodeSandbox</h1>
      <h2>Value is {ref.current}</h2>
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
}

The current behavior

eslint-plugin-react-hooks does not report an issue.

The expected behavior

eslint-plugin-react-hooks should report an issue, namely that the createRef should be useRef.

danvk avatar Apr 13 '21 21:04 danvk

IMO this does seem like something that should be warned about, but it also seems odd for eslint-plugin-react-hooks to warn about it (since those rules are all about hooks and createRef is not a hook).

bvaughn avatar Apr 13 '21 23:04 bvaughn

useRef is a hook tho - it’d be a rule about migrating a use case to hooks, which seems appropriate.

ljharb avatar Apr 13 '21 23:04 ljharb

Is eslint-plugin-react-hooks open to external contributors? I've written this hook for our codebase and would like to commit it upstream here.

NotWoods avatar Dec 15 '23 16:12 NotWoods