writingsabout

A

AZRULAZIZ

JavaScript Developer

React: useCallback hooks simple explanation

16 June, 2019

useCallback(function, [dependecies])

useCallback is one of the new features introduced in the react hooks API. Personally the name is quite confusing because callback is usually referred to asynchronous functions, the function that we invoke whenever a certain operation has finished. useCallback however is used for a different purpose.


So what does it do? According to React official docs, it Returns a memoized callback. In simpler words, it returns a cached version of a function. Basically this hook is mainly use for performance reason (memory-wise). How does it do that? lets see an example:

const [height, setHeight] = useState(100)
const [age, setAge] = useState(3)

const handleSetHeight = () => setHeight(height + 10)
const handleSetAge = () => setAge(age + 1)

We setup two useState hooks & declare two functions to handle state changes. This seems normal. The issue here is that everytime we invoke a function and re-render happens, a new instance of both of these functions will be created. Even if we invoke only one function, the instance of the other function will also be created. Imagine if there are more functions, how many instance have to be created during each re-render. Its redundant & causes performance issues.


useCallback helps in solving this issue. It will cache/memoized function that we pass to it. For example, lets rewrite both function above like this:

const handleSetHeight = useCallback(() => setHeight(height + 10), [height])
const handleSetAge = useCallback(() => setAge(age + 1), [age])

By doing this, whenever we invoke a function and re-render happens, a new function instance will only be created for that particular function that is being invoked. No new instance is created for the other function. The second argument passed to useCallback, the dependecies array plays a major part. A new function instance will only be generated if any value of the variable inside that array changes between re-rendering. If nothing changes, useCallback will just return the cached version of the function instance.


Basically this is what useCallback hook is used for. To prevent unnecessary operation and improve performance.