Skip to main content

UseCallback

The useCallback hook in React is used to memoize a function so that it is only re-created when its dependencies change. This is particularly useful when passing functions as props to child components, helping to avoid unnecessary re-renders of those children.

Syntax

const memoizedCallback = useCallback(() => {
// Function logic here
}, [dependencies]);`
  • Function: The function to be memoized.
  • Dependency Array: A list of dependencies that determine when the function should be re-created. If any of these dependencies change, the function is updated; otherwise, it remains the same across renders.

Example: Optimizing Child Component Re-renders

In this example, useCallback is used to prevent the increment function from being recreated unnecessarily, which helps optimize performance by avoiding unnecessary re-renders of the Child component.

import React, { useState, useCallback } from 'react';

function Parent() {
const [count, setCount] = useState(0);
const [otherCount, setOtherCount] = useState(0);

// Memoize the increment function to prevent unnecessary re-renders
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setOtherCount(otherCount + 1)}>Increment Other Count</button>
<p>Other Count: {otherCount}</p>
<Child increment={increment} />
</div>
);
}

function Child({ increment }) {
console.log("Child component rendered");

return (
<div>
<button onClick={increment}>Increment Count in Parent</button>
</div>
);
}

export default Parent;`

Explanation

  1. Memoized Function: The increment function is wrapped in useCallback, so it only changes if count changes.
  2. Avoiding Re-Renders in Child: Because increment is memoized, it won't be recreated when otherCount changes, which means the Child component will not re-render unless the actual function reference (increment) changes.
  3. Optimization: useCallback helps to prevent unnecessary re-renders of Child by ensuring the function reference remains the same when otherCount changes, reducing performance overhead.

When to Use useCallback

  • Use useCallback when passing functions to components that depend on reference equality to prevent unnecessary re-renders.
  • It's useful in conjunction with React.memo, which only re-renders a component if its props change, making useCallback an efficient way to keep function references stable.