DEV Community

Jakub Jadczyk
Jakub Jadczyk

Posted on

useMemo and useCallback

Main reason to use it

The essential idea with useMemo and useCallback is that it makes possible to "remember" a computed value / callback between renders. So we want to use it as a prevention against re-rendering which can use resources in a unwanted way.

useMemo

const calculation = useMemo(()=>{
   heavyCalculation(count)
},[count])
Enter fullscreen mode Exit fullscreen mode

The useMemo Hook accepts a second parameter to declare dependencies. The expensive heavyCalculation function will only run when its dependencies have changed. It will check if the parameter "count" has changed. If not the function will not be re-rendered.

useCallback

const calculation = useCallback((id)=>{
   setUsers(users.filter((user) => user.id !== id))
},[users])
Enter fullscreen mode Exit fullscreen mode

The useCallback Hook also accepts a second parameter to declare dependencies. That's the biggest difference between useMemo and useCallbackis are that the first one get function and return memoized value, the second get function and returns memoized callback.

Top comments (0)