What is the useCallback() hook in React and when to use it?
The useCallback() hook is a useful feature in React that let's you memoize functions so that they're not recreated unnecessarily. 📞
Normally, when you define functions inside a functional component, a new memory reference for that function gets created. When you pass a function into useCallback, it applies memoization to return a memoized version of the function if one of the dependencies change. This saves repeated creations of the function whenever the component re-renders.
This is particularly useful when you define a function that's specified in the dependency array of the useEffect. The function memory reference changes on every re-render which then triggers another render via useEffect. To avoid this, we memoize the function using useCallback().
Memoization is a useful trick to improve performance of your React applications. However, the dangers of doing memoization wrong are worse than not using it at all because memoization is extra computation because the application has to check the cache, store results and manage the cache. Moreover, if you use memoization with an incorrect dependency array, it might not work how it's expected or even cause memory leaks in your application!
This brings me to React.memo(), I'll write a separate post on this, but useCallback is used frequently with React.memo. React.memo() caches the component and uses the cached version if the props change, but are not used in the rendering logic. If you pass a non memoized function to a memo component, it'll not work as expected!
Here are some good resources to understand useCallback better:
https://stackoverflow.com/questions/71265042/what-is-usecallback-in-react-and-when-to-use-it
https://www.angularminds.com/blog/understanding-the-benefits-of-reactmemo-for-functional-components
https://www.knowledgehut.com/blog/web-development/all-about-react-usecallback
— AdiPat ✨
If you're looking for someone to build your startup MVP, contact me!
I actively work on Open Source Software, check out my GitHub Profile. ✨
Follow me on Instagram (@adityapatange), I talk about tech, meditation, startups and hip hop! ⚡️
I write byte-sized insights on Threads to supercharge your day. 💡