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

Rule proposal: Prefer memoized callback functions #3683

Open
oliveryasuna opened this issue Jan 21, 2024 · 1 comment
Open

Rule proposal: Prefer memoized callback functions #3683

oliveryasuna opened this issue Jan 21, 2024 · 1 comment

Comments

@oliveryasuna
Copy link

Consider the following:

// Option 1.
const MyComponent = () => {
  return <div onClick={() => console.log('clicked')}>Click me</div>;
};

// Option 2.
const MyComponent = () => {
  const handleClick = () => {
    console.log('clicked');
  };
  
  return <div onClick={handleClick}>Click me</div>;
};

Both options behave the same. The callback is recreated on every re-render. One might prefer to memoized the callback to avoid this common pitfall:

// Option 3.
const MyComponent = () => {
  const handleClick = useCallback(() => {
    console.log('clicked');
  }, []);

  return <div onClick={handleClick}>Click me</div>;
};

I propose a new rule that reports when a callback function is defined in JSX or would be recreated on every re-render. More generally, such a rule could allow developers to prefer one pattern over the other.

Note: I opened this issue is conjunction with #3682.

@ljharb
Copy link
Member

ljharb commented Jan 29, 2024

I agree (when using React >= 16.9) there's value in ensuring that any function created in the render path is memoized with useCallback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants