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 #3682

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

Rule proposal: Prefer memoized callback functions #3682

oliveryasuna opened this issue Jan 21, 2024 · 1 comment

Comments

@oliveryasuna
Copy link

oliveryasuna commented Jan 21, 2024

Consider the following:

type MyComponentProps = {
  onClick?: (event: React.MouseEvent<HTMLDivElement>) => void
};

const MyComponent = (props: MyComponentProps) => {
  return <div onClick={props.onClick}/>;
};

If props.onClick changes frequently and/or changes on every parent render, it will cause the child component to re-render. Therefore, one may want to memoized the callback:

const MyComponent = ((props: MyComponentProps) => {
  const handleClick = useCallback(
      ((event: React.MouseEvent<HTMLDivElement>) => {
        props.onClick?.(event);
      }),
      [props.onClick]
  );
  
  return (<div onClick={handleClick}/>);
});

If props.onClick changes on every parent render, e.g., it is defined inline (onClick={() => doSomething()}) without memoization, handleClick will change on every render as well, mirroring the pitfall of the first example. However, by memoizing handleClick, one has more control over re-renders if props.onClick is stable, i.e., it is not recreated on every parent render.

I propose a new rule that reports when a prop is used directly as a callback function. More generally, such a rule could allow developers to prefer one pattern over the other.

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

@ljharb
Copy link
Member

ljharb commented Jan 29, 2024

@oliveryasuna While in general this is correct, for HTML elements that's not actually true - React is smarter than that. It's only functions passed as props to custom elements that need to be memoized.

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