'Does useCallback make sense for not memoized components?
During reconciliation react compares trees and gets differences. Does it make sense to decrease those differences by using memoization hooks when components are not memoized?
Example:
// Does useCallback make sense here?
const onPress = useCallback(() => console.log('Press!'), []);
return (
<Pressable onPress={onPress}/> // Pressable is neither a memoized FC nor a PureComponent
)
EDIT: Would be nice to receive some numbers, e.g. performance decrease/improvement in ms, and especially for react native.
Solution 1:[1]
So react automatically have a memoize system that checks the diffs of all components props when rendering, regardless of your component being memorized. With this system react checks on only the primitive types (Number, String, Boolean, etc).
But if you pass a function as props and want react to memoize that function calls then the useCallback becomes useful.
Solution 2:[2]
No. React is way too fast in general. useCallback
and useMemo
are supposed to be used only when required.
Note: "Premature optimization is the root of all evil" ref
useCallback
and useMemo
come with their own overheads. Check this, Kent C Dodds goes in more depth about this.
Think about it this way:
When you scroll a webpage, numerous re-renders keep happening. Even during certain animations there are lot of re-renders but we don't face performance issues due to the speed of browser.
Just to cover extreme cases I'd also suggest you a read of layout thrashing and debounce input handlers
Solution 3:[3]
I don't think so. This is the example in the React.org site.
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
Here [a, b] is a dependency list. This means callback is called automatically when a or b has changed. It seems to be not called like yours. You passed no dependencies and callback will not be called. I think you can change in this way if you wanna use callback.
const [pressed, setPressed] = useState(false)
useCallback(() => console.log('Press'), [pressed])
return (
<Pressable onPress={() => setPressed (pressed => !pressed) } />
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ritchid Amoah |
Solution 2 | Shravan Dhar |
Solution 3 | Chuck |