DEV Community

kazuki
kazuki

Posted on

Understanding useCallback in React

If you've been working with React function components, you might have heard about useCallback. But what exactly does it do and why is it useful? Let's break it down simply.

The Challenge with Function Components
In React, function components re-run entirely on every re-render. This means that any functions you define inside your component are also recreated from scratch each time the component updates.

While this behavior is usually fine, it can lead to performance issues, especially when you pass these functions down as props to child components.

Enter useCallback: Memoizing Your Functions
This is where useCallback comes in handy. It's a React Hook that lets you memoize a function. In simple terms, it "remembers" your function.

import React, { useCallback } from 'react';

function MyParentComponent() {
  const handleClick = useCallback(() => {
    // This function will only be recreated if its dependencies change
    console.log('Button clicked!');
  }, []); // Empty dependency array means it's created once

  return <MyChildComponent onClick={handleClick} />;
}
Enter fullscreen mode Exit fullscreen mode

By wrapping your function with useCallback, React will provide the same function instance on subsequent renders, as long as the values in its dependency array haven't changed.

Why Memoize Functions?
The primary benefits of using useCallback include:

  • Preventing Unnecessary Child Re-renders: If you pass a function to a child component that is itself memoized (e.g., with React.memo), useCallback ensures that the child doesn't re-render just because the parent re-rendered and created a "new" function instance.

  • Optimizing useEffect and useMemo: When functions are part of the dependency arrays for useEffect or useMemo, useCallback helps prevent those hooks from running unnecessarily, as it ensures the function reference remains stable.

When to Use It?
You don't need useCallback for every function. It adds a small overhead. Focus on using it when:

You're passing callback functions to memoized child components (e.g., using React.memo).

The function is part of a dependency array for useEffect or useMemo, and its stability is crucial.

By understanding and selectively applying useCallback, you can write more performant and stable React applications.

Top comments (0)