Hey you! Don’t use #React useCallback (or useMemo) for all your callback props, thinking it will improve performance, because it won’t. Here's why - 1/n
For every #React `useCallback` call you make, the browser does some work. For a a simple callback, with a fast component, adding the `useCallback` has little or no benefit, and even has a little performance cost. 2/n
@kentcdodds explains this in “When to useMemo and useCallback” - (kentcdodds.com/blog/usememo-a…) and yet I still run into people saying “We should be wrapping <misc callback> in `useCallback`” arbitrarily, with the mistaken notion it will improve performance. 3/n
“Trust, but verify” - To show how `useCallback` impacts performance, I ran benchmarks using the #React Devtools profiler: Adding `useCallback` to a simple/fast component does not improve perf., and sometimes was slower. On average they were about the same. 4/n
Side note - I recommend running benchmarks at least 10 times and taking an average, because there will always be some variation in results. 5/n
Here is one example from the benchmarks I ran comparing with/without `useCallback`. The `useCallback` version was slower to render. This varied across each iteration, and overall the performance was similar for both versions. 6/n
Why has it been said that you should use `useCallback` to improve performance? Because there are very specific cases where `useCallback` can be a tool to help improve performance. For example - 7/n
If we have a slow rendering component, then we’ll want to avoid any extra rendering: make sure the props pass an equality check, and use `React.memo`. Using #React `useCallback` on callback props will ensure that the callback passes the equality check, avoiding re-render. 8/n
This codepen (codepen.io/paradasia/pen/…) demonstrates when/why you'd `useCallback` to improve perf. - but this is a very specific use case. But getting back to the original point about #React `useCallback`, which applies in the same way to `useMemo` - 9/n
tldr; Don’t go around arbitrarily wrapping every single callback prop in #React useCallback, because that won’t improve performance.
Thank you.
10/n
Bonus - this post from @rhagigi explains it all, with more detail and eloquence. 11/n
Finally listened to the React 18 Working Group Twitter Space, and it provides a nice over of the plans/features coming in React 18!
Curious but busy? Check out my summary in 12 tweets~ 🧵
1/12 React 18 alpha was published, and has exciting new features. For now, you don’t need to read more unless you are curious and/or if you are a library author/educator who wants to get a head start. Details in the blog post - reactjs.org/blog/2021/06/0…
2/12 The React team has created a React 18 working group with the goal of providing support to, and getting feedback from, the React community and library authors in a transparent way. It’s a diverse and friendly group. Check it out if you are curious! github.com/reactwg/react-…