When to useMemo and useCallback?
Bunlong
React Patterns TeamReact library provides us two built-in hooks to optimize the performance of our applications are useMemo
and useCallback
.
The usage of this two built-in hooks is quite similar so it can get confusing about when to use each. To clear that confusion, let's dig in and understand the actual difference and the correct way to use them both.
#
Differences#
useMemo- Call a function and return its result
- Uses reference equality to prevent unnecessary renders
#
useCallback- Call a function and return the function without calling it
- Prevent a function from being recreated when app is rerendered
#
Similars- Both return a new value, just when one of the dependencies value changes
- 1st argument: a function
- 2nd argument: an array of dependencies