Day 15 of 50 Days of React: useCallback Hook in React?

Aman Khan
2 min readJul 31, 2022

--

What is useCallback Hook in React?

A. The React useCallback returns a Memoized Callback Function😁.

Think of Memoization as caching a value so that it does not need to be recalculated.

This allows us to isolate resource-intensive functions so that they will not automatically run on every render😮.

The useCallback only runs when one of its dependencies updated🙄.

This can improve performance.

The useCallback and useMemo hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function😅.

UseCase📝

One reason to use useCallback is to prevent a component from re-rendering unless its props have changed👌🏻.

In this case, if we don’t use useCallback then whenever the Counter component changes all the functions inside it i.e increment, decrement, incrementOtherCounter will get reinstantiated.

So to prevent that we can use useCallback.

const { useState, useCallback } = Reactconst Counter = () => {
const [count, setCount] = useState(0)
const [otherCounter, setOtherCounter] = useState(0)

const increment = useCallback(() => {
setCount(count + 1)
}, [count])
const decrement = useCallback(() => {
setCount(count - 1)
}, [count])
const incrementOtherCounter = useCallback(() => {
setOtherCounter(otherCounter + 1)
}, [otherCounter])

return (
<>
Count: {count}
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={incrementOtherCounter}>incrementOtherCounter</button>
</>
)
}
ReactDOM.render(<Counter />, document.getElementById('app'))

In the next article I will be writing about useMemo Hook🤔 ?

That’s all for Today, Stay Tuned and I will see you in the next one👋🏻.

Link to Day 16

Thanks for Following and Claps😋

--

--

Aman Khan

Blockchain and Web3 Engineer Crafting compelling stories at the intersection of tech, business, and culture.