useCallback VS useMemo in two lines

TLDR

useCallback: “cache a function in a functional component”

useMemo: “cache an attribute in a functional component”

Photo by Anastasiia Krutota on Unsplash

General Usecase

“I don’t want my child component to be re-rendered if only part of my state that are irrelevant to my child component has changed”

You will start to think of those scenarios when you start to do consider performance improvement, however, the improvement can only be achieved if update the attribute or perform the function is expensive.

Normally we should aviod use useMemo or useCallback because it caches stuff and drag your app down if you overuse them.

How does a useCallback looks like?

It can be as simple as the following:

const callbackClick = React.useCallback(() => {// Do something here}, [color]);

This is to say, only color changes the component that reference the callbackClick function will be updated.

How does a useMemo looks like?

It can be as simple as following:

const style = React.useMemo(() => ({ color: color }), [color]);

This is to say, only color change the component that reference the color attribute will be updated.

Important Note

To achieve the goal of avoiding re-render a child component, you should wrap your component into React.memo

Example in the sandbox

If you click the count button, the child component won’t be updated because they only depend on color change

Example link: https://codesandbox.io/s/cocky-tesla-gpl1c?file=/src/App.js:185-248

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store