How to use React.memo and useCallback

In this article, I’ll talk about when and how to use React.memo and the useCallback hook. After this article, you will understand when to use useCallback. Learn how React.Memo and useCallback work together.

Briefly about React.memo and useCallback

React.Memo is a higher-order component. Similar to React.PureComponent, but intended for functional components.

Higher-order component — the function takes a child component and parameters, and then creates a container on top of the child component.

React.PureComponent — similar to React.Component, but the only difference in the shouldComponentUpdate method.

useCallback — the hook will return a memoized callback function, which changes only if the values ​​from the dependencies change.

Examples

Base — Doesn’t use React.Memo. The component will be rendered every time.

let count = 0
export default function Base({ action }) {
.log(`${++count} Base component`)
return <h3 onClick={action}>Base</h3>
}

Memo — uses React.Memo. The component will be rendered every time the properties change.

let count = 0
export default React.memo(function Memo({ action }) {
.log(`${++count} Memo component`)
return <h3 onClick={action}>Memo</h3>
})

NoUseCallback — do not use useCallback. Base and Memo components are rendered every time

export default function NoUseCallback() {
const [a, setA] = useState('')
const [b, setB] = useState('')

useEffect(() => {
setTimeout(() => {
.log('change value not related to action')
setA('a')
}, 1000)

setTimeout(() => {
.log('change value related to action')
setB('b')
}, 3000)
}, [])

const action = () => .log(b)
return (
<>
<Base action={action} />
<Memo action={action} />
</>
);
}

Console:

1 Base component
1 Memo component
change value not related to action
2 Base component
2 Memo component
change value related to action
3 Base component
3 Memo component

UseCallback — use the useCallback method. Rendered Base 3 and Memo 2 times

export default function UseCallback() {
const [a, setA] = useState('')
const [b, setB] = useState('')

useEffect(() => {
setTimeout(() => {
.log('change value not related to action')
setA('a')
}, 1000)

setTimeout(() => {
.log('change value related to action')
setB('b')
}, 3000)
}, [])

const action = useCallback(() => {
.log(b)
}, [b]);

return (
<>
<Memo action={action} />
<Base action={action} />
</>
);
}

Console:

1 Memo component
1 Base component
change value not related to action
2 Base component
change value related to action
2 Memo component
3 Base component

Conclusion

We use React.Memo when we want the component to be re-rendered when props or specific props change.
We wrap the function in useCallback when we pass it to other components or when external variables are used

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