Rel1cx / eslint-react

A series of composable ESLint plugins for libraries and frameworks that use React as a UI runtime.
https://eslint-react.xyz
MIT License
242 stars 10 forks source link

Feedback for “ensure-use-callback-has-non-empty-deps” #605

Closed bhollis closed 2 months ago

bhollis commented 3 months ago

This rule is not always applicable - functions cannot be hoisted if they depend on (capture) any other variable. If they are not wrapped in useCallback, they will not be stable.

Example

function MyComponent() {
  const [showSnapshot, setShowSnapshot] = useState(false);
  const handleSnapshot = useCallback(() => setShowSnapshot(true), []);

  return <OtherComponent onClick={handleSnapshot}>{showSnapshot ? 'Snapshot' : 'Nothing'}</OtherComponent>
}

In this example, handleSnapshot must be wrapped in useCallback to be stable, but it cannot be hoisted out of the function because it uses setShowSnapshot. I could add setShowSnapshot to the dependencies list, but it's a known-stable reference (from useState) and thus doesn't need to be provided.