Popular Searches
Popular Course Categories
Popular Courses

useCallback Hook

useCallback Hook

Advanced React Hooks

useCallback Hook in React JS – Complete Detailed Notes

The useCallback Hook is a built-in React Hook used to cache a function definition between component re-renders. It helps optimize performance when a function is passed as a prop to a child component or used as a dependency in another Hook.

In React, a component can re-render when its state or props change. During rendering, functions declared inside the component are generally recreated. The useCallback Hook can preserve the same function reference until one of its dependencies changes.

1. What Is the useCallback Hook?

useCallback is a React Hook that returns a cached version of a function when its dependencies have not changed. It is mainly used for performance optimization and can work together with React.memo to help prevent unnecessary child component re-renders.

Definition: The useCallback Hook allows React developers to reuse a function reference across renders until its dependencies change.

Basic Syntax

import { useCallback } from 'react';

const cachedFunction = useCallback(() => {
  // Function logic
}, [dependencies]);

Syntax Explanation

  • useCallback: The React Hook used to cache a function definition.
  • Function: The function you want React to cache.
  • Dependencies: An array of reactive values used inside the function, such as props, state, and variables declared in the component.
  • Cached function: The function reference returned by React when the dependencies have not changed.

2. Why Do We Need useCallback?

Consider a parent component that contains a function and passes it to a child component. When the parent re-renders, the function is usually recreated. Even if the function performs the same task, its reference is different.

If the child component uses React.memo, the new function reference can make React consider the child's props changed, causing another render.

Example Without useCallback

import { useState, memo } from 'react';

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

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

  function handleClick() {
    console.log('Child button clicked');
  }

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

export default App;

Explanation: Every time the count changes, the App component re-renders and creates a new handleClick function. The Child component receives a different function reference, so its memo optimization cannot skip that render.

3. Example Using useCallback

We can wrap the function in useCallback so React can reuse the same function reference while its dependencies remain unchanged.

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

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

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

  const handleClick = useCallback(() => {
    console.log('Child button clicked');
  }, []);

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

export default App;

How This Example Works

  1. The App component renders for the first time.
  2. The useCallback Hook creates and returns the function reference.
  3. The Child component receives that function through the onClick prop.
  4. When the count changes, the App component re-renders.
  5. Because the dependency array is empty, React can reuse the cached function reference while its cache is retained.
  6. Since the Child component's function prop remains the same and its other props have not changed, React.memo can skip the unnecessary child render.

Important: useCallback alone does not stop a component from re-rendering. It preserves a function reference. Skipping a child render generally requires an optimization such as React.memo, and the child's other props must also remain unchanged.

4. Understanding the Dependency Array

The dependency array tells React which reactive values the function uses. React compares each dependency with its previous value using Object.is. If a dependency changes, React returns the new function definition from the current render.

Dependency Syntax Meaning
[] No reactive dependencies. React can reuse the cached function while the cache is retained.
[count] The function reference can be reused while count remains unchanged.
[count, name] The function reference can be reused while both count and name remain unchanged.
Dependency array omitted Incorrect for normal memoization: useCallback returns a new function on each render.

Example With a State Dependency

import { useState, useCallback } from 'react';

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

  const showCount = useCallback(() => {
    console.log('Current count:', count);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
      <button onClick={showCount}>Show Count</button>
    </div>
  );
}

export default Counter;

Explanation: The function uses the count state, so count must be included in the dependency array. When count changes, React returns the function created during the latest render, which sees the updated count value.

5. Using useCallback With State Updates

Sometimes, a callback needs the previous state to calculate the next state. A functional state updater can reduce the number of dependencies required.

Example: Add Items to a List

import { useState, useCallback } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]);

  const addTodo = useCallback((text) => {
    const newTodo = {
      id: Date.now(),
      text: text
    };

    setTodos(previousTodos => [...previousTodos, newTodo]);
  }, []);

  return (
    <div>
      <button onClick={() => addTodo('Learn React')}>
        Add Todo
      </button>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;

Explanation: The callback does not read the current todos variable directly. Instead, it passes an updater function to setTodos. React supplies the previous state to that updater, so the callback does not need todos in its dependency array.

Note: This example uses Date.now() for a simple demonstration. In a production application, use an ID-generation approach suitable for the project and avoid relying on timestamps alone when uniqueness is important.

6. useCallback With React.memo

React.memo is a higher-order component that can skip rendering a component when its props have not changed. When a function is passed as a prop, useCallback can help keep that prop stable.

Example

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

const UserProfile = memo(function UserProfile({ onGreet }) {
  console.log('UserProfile rendered');

  return (
    <button onClick={onGreet}>
      Greet User
    </button>
  );
});

function App() {
  const [theme, setTheme] = useState('light');

  const greetUser = useCallback(() => {
    alert('Hello, welcome to React!');
  }, []);

  return (
    <div className={theme}>
      <button onClick={() => {
        setTheme(current =>
          current === 'light' ? 'dark' : 'light'
        );
      }}>
        Change Theme
      </button>

      <UserProfile onGreet={greetUser} />
    </div>
  );
}

export default App;

When the theme changes, App re-renders. The greetUser function reference remains stable, so UserProfile can skip re-rendering if its other props remain unchanged. In this example, the theme class is applied to the parent, not passed to UserProfile.

7. useCallback With useEffect

A function defined inside a component is recreated on each render. If an Effect depends on that function, the Effect may run more often than expected. useCallback can stabilize the function reference when necessary.

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

function SearchExample({ category }) {
  const [query, setQuery] = useState('');

  const getSearchOptions = useCallback(() => {
    return {
      category: category,
      query: query
    };
  }, [category, query]);

  useEffect(() => {
    const options = getSearchOptions();
    console.log('Search options:', options);
  }, [getSearchOptions]);

  return (
    <input
      value={query}
      onChange={event => setQuery(event.target.value)}
      placeholder="Enter search text"
    />
  );
}

export default SearchExample;

Explanation: The function reference changes when category or query changes. The Effect runs when that function reference changes. For a real Effect, include the appropriate setup and cleanup logic if needed.

Best practice: If a function is only needed inside an Effect, consider declaring it inside the Effect instead. This can make the code simpler and eliminate the need for useCallback.

8. Difference Between useCallback and useMemo

Feature useCallback useMemo
Purpose Caches a function reference. Caches the result of a calculation.
Returns The function itself. The calculated value.
Typical use Stabilizing callback props or Hook dependencies. Avoiding repeated expensive calculations.
Example useCallback(() => save(id), [id]) useMemo(() => calculateTotal(items), [items])

9. Difference Between useCallback and React.memo

Feature useCallback React.memo
Type React Hook. Higher-order component.
Optimizes Function identity. Component rendering based on props.
Used for Keeping a function reference stable. Skipping eligible re-renders when props remain unchanged.
Works together? Yes, can stabilize function props. Yes, can skip a child render when its props are unchanged.

10. Common Mistakes When Using useCallback

Mistake 1: Forgetting Dependencies

// Incorrect: count is used but not listed
const showCount = useCallback(() => {
  console.log(count);
}, []);

Problem: The function may keep reading a stale count value.

Correction:

const showCount = useCallback(() => {
  console.log(count);
}, [count]);

Mistake 2: Using useCallback Everywhere

Not every function needs memoization. For simple functions that are not used in a performance-sensitive situation, useCallback can add complexity without providing a meaningful benefit.

Mistake 3: Expecting useCallback to Prevent All Re-Renders

useCallback does not stop the component containing it from rendering. It also does not automatically prevent child renders. For child-render optimization, React.memo may be useful when the child's props are stable.

Mistake 4: Calling useCallback Inside a Loop or Condition

// Incorrect
if (enabled) {
  const handler = useCallback(() => {
    console.log('Enabled');
  }, []);
}

Correction: Call Hooks at the top level of a React component or custom Hook, not inside loops, conditions, or nested functions.

Mistake 5: Using an Empty Dependency Array Without Checking the Function

An empty array is suitable only when the callback does not need changing reactive values from the component. If the callback reads changing props or state, include those dependencies or use an appropriate state updater.

Mistake 6: Mutating State

useCallback does not make state mutations safe. When updating arrays or objects, create new values rather than modifying existing state directly.

11. Rules of the useCallback Hook

  • Import useCallback from React before using it.
  • Call it at the top level of a component or custom Hook.
  • Pass a function as the first argument.
  • Pass a dependency array as the second argument for memoization.
  • Include every reactive value used by the callback in the dependency array.
  • Do not call the callback as part of the useCallback declaration; React returns the function for you to call later.
  • Use it primarily as a performance optimization, not as a requirement for correct application logic.
  • Use React Developer Tools Profiler to identify actual performance issues before adding unnecessary memoization.

12. Practical Project: Counter With a Memoized Child

This mini-project demonstrates how useCallback can keep a button handler stable while a parent component updates its counter.

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

const ActionButton = memo(function ActionButton({ onAction }) {
  console.log('ActionButton rendered');

  return (
    <button onClick={onAction}>
      Run Action
    </button>
  );
});

function CounterApp() {
  const [count, setCount] = useState(0);
  const [message, setMessage] = useState('');

  const runAction = useCallback(() => {
    setMessage('Action completed successfully!');
  }, []);

  return (
    <div>
      <h2>Counter Application</h2>
      <p>Count: {count}</p>

      <button onClick={() => setCount(value => value + 1)}>
        Increase Count
      </button>

      <ActionButton onAction={runAction} />

      <p>{message}</p>
    </div>
  );
}

export default CounterApp;

Project Explanation

  1. The counter state stores the current number.
  2. The message state stores the result of the child action.
  3. The runAction function is cached with useCallback.
  4. ActionButton is wrapped in React.memo.
  5. When the counter changes, ActionButton can skip rendering because its onAction prop remains the same and no other props change.
  6. When the action button is clicked, the message updates and the parent renders again. React can still skip ActionButton if its props remain unchanged.

13. Advantages of useCallback

  • Helps maintain stable function references between renders.
  • Can support React.memo optimizations for child components.
  • Can help prevent unnecessary Effect re-runs when a function dependency is genuinely needed.
  • Can make callback dependencies more predictable when used correctly.
  • Useful in some custom Hooks that return functions to their consumers.

14. Limitations of useCallback

  • It does not automatically make every component faster.
  • It does not stop the component using the Hook from re-rendering.
  • Incorrect dependencies can cause stale values or reduce the intended optimization.
  • Excessive memoization can make code harder to read and maintain.
  • React may discard a cached function in certain circumstances, so application correctness must not depend on the cache being permanent.
  • In supported configurations, the React Compiler can automatically memoize values and functions, reducing the need for manual useCallback calls.

15. Frequently Asked Interview Questions

Q1. What is useCallback in React?

useCallback is a React Hook that caches a function definition between re-renders until its dependencies change.

Q2. Why is useCallback used?

It is used to preserve a function reference, particularly when passing callbacks to memoized child components or using functions as Hook dependencies.

Q3. Does useCallback prevent a component from re-rendering?

No. It caches a function reference. The component can still re-render when its state, props, or context changes.

Q4. What is the purpose of the dependency array?

The dependency array tells React which reactive values the callback uses and when the cached function should be replaced with the new function definition.

Q5. What happens if the dependency array is empty?

The callback has no reactive dependencies. React can reuse the cached function while its cache is retained.

Q6. What happens if a dependency changes?

React returns the function definition from the current render, updating the cached function reference.

Q7. What is the difference between useCallback and useMemo?

useCallback caches a function reference, whereas useMemo caches the result of a calculation.

Q8. Can useCallback be used with React.memo?

Yes. useCallback can keep a function prop stable so that React.memo can skip an eligible child re-render when the other props also remain unchanged.

Q9. Can useCallback be called inside a loop?

No. Hooks must be called at the top level of a component or custom Hook, not inside loops or conditions.

Q10. Should useCallback be used for every function?

No. Use it when stable function identity provides a real benefit. Avoid unnecessary memoization that adds complexity without improving performance.

Q11. Can useCallback access state?

Yes. If the callback reads reactive state, include that state in its dependency array or use a suitable functional state updater when appropriate.

Q12. Is useCallback required for event handlers?

No. Most event handlers work correctly without useCallback. It is primarily a performance optimization.

16. Practice Exercises

  1. Create a counter component and use useCallback to cache a function that logs the current count.
  2. Create a child button wrapped with React.memo and pass a callback from its parent.
  3. Build a todo list with an addTodo function using a functional state updater.
  4. Create a search form that passes a memoized submit handler to a child component.
  5. Compare the console output with and without useCallback and React.memo.
  6. Inspect a component with React Developer Tools Profiler and identify whether memoization improves performance.

17. Quick Revision Checklist

  • ☑ useCallback caches a function reference.
  • ☑ Syntax: useCallback(function, dependencies).
  • ☑ Dependencies are compared using Object.is.
  • ☑ Every reactive value used by the function must be considered in the dependency array.
  • ☑ useCallback and React.memo can work together.
  • ☑ useCallback does not prevent the parent component from rendering.
  • ☑ useCallback caches a function; useMemo caches a calculation result.
  • ☑ Hooks must be called at the top level.
  • ☑ Memoization should be used when it provides a real performance benefit.

18. Official React Documentation

19. React JS Training Resources

To learn React JS concepts such as Hooks, component rendering, state management, and performance optimization, explore the following training resources:

20. Conclusion

The useCallback Hook is an important React performance optimization tool. It helps preserve function references between renders when dependencies have not changed. It is especially useful with React.memo and in situations where a function is a dependency of another Hook. However, it should not be used automatically for every function. Understand the component's rendering behavior, specify dependencies correctly, and use profiling tools to determine whether memoization is beneficial.

Previous Next
whatsapp