DEV Community

Jakub Jadczyk
Jakub Jadczyk

Posted on

3 2

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay