Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bhollis opened this issue Jun 29, 2024 · 0 comments
Open

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

bhollis opened this issue Jun 29, 2024 · 0 comments
Labels
issue tracker needs investigation Further investigation is required

Comments

@bhollis
Copy link

bhollis commented Jun 29, 2024

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.

@Rel1cx Rel1cx added bug Something isn't working needs investigation Further investigation is required issue tracker and removed bug Something isn't working labels Jun 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
issue tracker needs investigation Further investigation is required
Projects
None yet
Development

No branches or pull requests

2 participants