In React, the main difference between useCallback and useMemo is that useCallback caches functions, while useMemo caches the results of functions:
useCallback | useMemo | |
|---|---|---|
What it caches | Functions | Results of functions |
When to use | To optimize the creation of callback functions passed to child components | To optimize and cache the result of a computation that depends on certain inputs |
- Prevents unnecessary re-renders of child components when their parent component re-renders. It does this by caching callback functions based on their dependencies.
- useMemo
- Prevents unnecessary recalculations and re-renders by caching the result of a function when its dependencies remain unchanged. This can be used to avoid executing expensive calculations.
useCallback vs useMemo:useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).With useCallback you memoize functions, useMemo memoizes any computed value:
const fn = () => 42 // assuming expensive calculation here
const memoFn = useCallback(fn, [dep]) // (1)
const memoFnReturn = useMemo(fn, [dep]) // (2)
(1) will return a memoized version of fn - same reference across multiple renders, as long as dep is the same. But every time you invoke memoFn, that complex computation starts again.
(2) will invoke fn every time dep changes and remember its returned value (42 here), which is then stored in memoFnReturn.
useCallback() and useMemo()
useCallback() and useMemo() are pretty much same but useCallback saves the function reference in the memory and checks on the second render whether it's same or not if it is same then it returns last saved function without recreating it and if it is changed then it returns a new function and replaces it with older function in memory for future rendering. useMemo works in same manner but it can't save your function but the computed or returned value. On every render useMemo checks the value if the returned value of your function is the same on second render then it will return same value without recalculating the function value and if the value is not same on second render then it will call the function and return new value and store it for future render.
Comments
Post a Comment