0
0
ReactConceptBeginner · 3 min read

What is useCallback in React: Explanation and Example

useCallback is a React hook that returns a memoized version of a callback function, preventing it from being recreated on every render unless its dependencies change. It helps optimize performance by avoiding unnecessary re-renders of child components that rely on stable function references.
⚙️

How It Works

Imagine you have a friend who always writes you a new letter every time you meet, even if the message is the same. This can be tiring to read repeatedly. useCallback works like asking your friend to keep the same letter until the message changes, so you don’t get a new letter every time.

In React, functions inside components are recreated on every render by default. This can cause child components that receive these functions as props to re-render unnecessarily. useCallback remembers the function and only updates it when its dependencies change, keeping the function stable across renders.

This helps React avoid extra work, making your app faster and smoother, especially when passing functions to components that rely on reference equality to decide if they should update.

đź’»

Example

This example shows a parent component using useCallback to memoize a function passed to a child. The child only re-renders when the function changes.

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

const Child = memo(({ onClick }) => {
  console.log('Child rendered');
  return <button onClick={onClick}>Click me</button>;
});

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

  const handleClick = useCallback(() => {
    alert('Button clicked!');
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <Child onClick={handleClick} />
    </div>
  );
}

export default Parent;
Output
When you click 'Increment', the count updates but 'Child rendered' does not log again because the memoized function stays the same. Clicking 'Click me' shows an alert.
🎯

When to Use

Use useCallback when you pass functions to child components that rely on reference equality to avoid unnecessary re-renders, such as components wrapped with React.memo. It is helpful in optimizing performance in large or complex React apps.

For example, if you have a list of items with buttons and each button uses a function from the parent, memoizing that function prevents all buttons from re-rendering when unrelated state changes.

However, avoid overusing useCallback for every function, as it adds complexity and some overhead. Use it mainly when you notice performance issues caused by frequent re-renders.

âś…

Key Points

  • useCallback memoizes functions to keep their identity stable across renders.
  • It helps prevent unnecessary re-renders in child components that depend on function props.
  • Use it with React.memo or similar optimizations.
  • Only use when performance benefits outweigh added complexity.
  • Dependencies array controls when the function updates.
âś…

Key Takeaways

useCallback memoizes a function to keep it from being recreated on every render.
It helps optimize React apps by preventing unnecessary child component re-renders.
Use it mainly when passing functions to memoized child components.
Always provide dependencies to control when the function updates.
Avoid overusing useCallback to keep code simple.