eslint-plugin-react-hooks should flag uses of createRef in function components
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
- Set up eslint-plugin-react-hooks and create a function component that uses
React.createRef. - 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.
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).
useRef is a hook tho - it’d be a rule about migrating a use case to hooks, which seems appropriate.
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.