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

Avoid defining functions within components #23

Open
eliasmalik opened this issue Sep 27, 2019 · 2 comments
Open

Avoid defining functions within components #23

eliasmalik opened this issue Sep 27, 2019 · 2 comments

Comments

@eliasmalik
Copy link

const randomise = array => {
array.sort(() => Math.random() - 0.5);
};

This function doesn't rely on any variables in its enclosing scope, so could be defined outside the component, which makes rendering more performant. Not a big deal for a small app, but good to know going forward.

If you did have a function that referenced variables in the enclosing scope (e.g. index), you can either make the function accept additional parameters or use useCallback which memoises functions defined within the component.

@eliasmalik
Copy link
Author

In fact this is a perfect example of something you'd use useCallback for:

onClick={() => {
if (index < 15) {
setIndex(index + 1);
}
}}

const Component = (props) => {
  const [index, setIndex] = useState(0);

  const onClick = useCallback(() => if (index < 15) setIndex(index + 1), [index]);

  return (
    <button onClick={onClick} />
  )
}

This also has the benefit of moving some application logic out of the markup, which is ideally as declarative as possible.

@oliverjam
Copy link

I would definitely advise using caution to avoid prematurely optimising for things like this though. E.g. useCallback/other types of memoization aren't free. Creating a tiny function every render is super fast in browsers nowadays, so I would only bother to do this if you had actually noticed a performance problem.

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

No branches or pull requests

2 participants