The Useless UseCallback

https://news.ycombinator.com/rss Hits: 8
Summary

I thought I'd written enough about memoization by now, but I feel there is one pattern I'm seeing a lot lately that makes me think otherwise. So today, I want to look at useCallback, and to some extent useMemo, in situations where I think they are totally pointless.Why memoize?There's usually only two reasons to create a memoized version of a function with useCallback or a value with useMemo:Performance optimizationSomething is slow, and slow is usually bad. Ideally, we'd make it faster, but we can't always do that. Instead, we can try to do that slow thing less often.In React, a lot of the time, the slow thing is re-rendering of a sub-tree, so we'd like to ideally avoid that if we think it's "not necessary".That's why we sometimes wrap components in React.memo, which is an uphill battle mostly not worth fighting, but still, it's a thing that exists.If we pass a function or a non-primitive value to a memoized component, we need to make sure that references to those are stable. That's because React compares the props of a memoized component with Object.is to check if it can skip rendering that sub-tree. So if the reference isn't stable, e.g. because it's newly created in each render, our memoization "breaks":Copyperformance-optimization: copy code to clipboard1function Meh() {2 return (3 <MemoizedComponent4 value={{ hello: 'world' }}5 onChange={(result) => console.log('result')}6 />7 )8}9 10function Okay() {11 const value = useMemo(() => ({ hello: 'world' }), [])12 const onChange = useCallback((result) => console.log(result), [])13 14 return <MemoizedComponent value={value} onChange={onChange} />15}Yes, sometimes the computation inside useMemo itself is slow, and we memoize to avoid those recomputations. Those useMemo calls are perfectly fine, too, but I don't think they are the majority of use-cases.Prevent effects from firing too oftenIf not passed as a prop to a memoized component, chances are our memoized value gets eventually passed as a dependency to an effect ...

First seen: 2025-07-28 21:34

Last seen: 2025-07-29 10:38