DEV Community

Megalraja
Megalraja

Posted on

Understanding useCallback in React

When I started learning React, I came across different hooks like useState, useEffect, and useRef. One hook that I wanted to understand better was useCallback.

At first, I wondered:

  • Why do we need useCallback?
  • What problem does it solve?
  • When should we use it?

Let's understand it step by step.

1. What is useCallback?

useCallback is a React Hook that memoizes a function.

In simple words, it helps React reuse the same function between renders instead of creating a new function every time.

Syntax:

const memoizedFunction = useCallback(() => {
    // Your logic
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

It takes two arguments:

  • A function.
  • A dependency array.

React returns the same function reference as long as its dependencies haven't changed.

2. Why do we need useCallback?

Let's look at a simple example.

import React, { useState } from 'react';

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

    const handleClick = () => {
        console.log("Button clicked");
    };

    return (
        <div>
            <h1>{count}</h1>
            <button onClick={() => setCount(count + 1)}>
                Increase
            </button>
            <button onClick={handleClick}>
                Click Me
            </button>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Every time the count state changes, the component re-renders.

During that render, JavaScript creates a new handleClick function.

This is where useCallback can help.

3. Using useCallback

Let's modify our example.

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

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

    const handleClick = useCallback(() => {
        console.log("Button clicked");
    }, []);

    return (
        <div>
            <h1>{count}</h1>
            <button onClick={() => setCount(count + 1)}>
                Increase
            </button>
            <button onClick={handleClick}>
                Click Me
            </button>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now React can reuse the same handleClick function between renders because the dependency array is empty.

4. Understanding the dependency array

The dependency array tells React when it should create a new function.

For example:

const handleClick = useCallback(() => {
    console.log(count);
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Here, count is a dependency.

  • If count doesn't change, React reuses the previous function.
  • If count changes, React returns a new function that uses the updated value.

Top comments (0)