useCallback Hook
What are useCallback Hooks in React?
`
`useCallback`
` is a React hook that is used to memoize functions, which helps in preventing unnecessary renders in your React components. It's particularly useful when working with child components that rely on function props. By using useCallback, you can avoid creating a new function instance on each render, optimizing performance.If we don't use `
`useCallback`
` function would run on every render. This helps us to memoize resource intensive functions so that they will not automatically run on every render.When to use `useCallback`:
If your function dependencies change frequently, and you notice unnecessary re-renders in child components, using
`useCallback`
can be beneficial.When you need to pass functions as props to child components, using
`useCallback`
ensures that the function reference doesn't change unless its dependencies change.Syntax :
app/page.tsx
1const cachedFn = useCallback(fn, dependencies)
Usage :
Call
`useCallback`
at the top level of your component to cache a function definition between re-renders:app/page.tsx
1import { useCallback } from 'react';
2
3export default function ProductPage({ productId, referrer, theme }) {
4 const handleSubmit = useCallback((orderDetails) => {
5 post('/product/' + productId + '/buy', {
6 referrer,
7 orderDetails,
8 });
9 }, [productId, referrer]);
Tip : You should only rely on useCallback as a performance optimization. If your code doesn’t work without it, find the underlying problem and fix it first. Then you may add useCallback back.