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” - ( https://kentcdodds.com/blog/usememo-and-usecallback) 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 ( https://codepen.io/paradasia/pen/qBpOxBR?editors=0011) 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 https://twitter.com/he_zhenghao/status/1504366946350862339
You can follow @ProvablyFlarnie.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: