Popular Searches
Popular Course Categories
Popular Courses

useCallback for Function References

useCallback for Function References

React Performance Optimization

useCallback for Function References in React – Complete Notes

1. Introduction to useCallback

useCallback is a React Hook that allows developers to cache a function definition between component re-renders. It helps maintain a stable function reference when the function's dependencies have not changed.

In React, functions defined inside a component are created again whenever that component renders. When these functions are passed as props to child components, the new function references may cause unnecessary re-renders, especially when the child component is optimized using React.memo.

The useCallback Hook helps avoid this problem by returning the previously cached function when its dependencies remain unchanged.

Official documentation: React useCallback Reference

2. Why Do We Need useCallback?

Consider a parent component that passes an event handler to a child component. Whenever the parent re-renders, a function defined inside it normally receives a new reference. Even if the function performs the same operation, React sees the new reference as a different prop.

This can cause unnecessary rendering work in memoized child components. The useCallback Hook can preserve the function reference until one of its dependencies changes.

  • Maintains stable function references between renders.
  • Can help prevent unnecessary re-renders of memoized child components.
  • Can help keep function dependencies stable in other Hooks.
  • Can improve performance in components with frequent updates.
  • Can simplify optimization of callbacks passed to reusable components.

3. Syntax of useCallback

const cachedFunction = useCallback(functionDefinition, dependencies);

Example:

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

Explanation:

  • useCallback: React Hook used to cache a function definition.
  • () => {...}: The function definition to cache.
  • []: The dependency array.
  • handleClick: The function reference returned by the Hook.

When the dependencies remain unchanged, React can return the same cached function reference on subsequent renders.

4. Understanding Function References

A function reference is the identity of a function object in JavaScript. Two functions can contain identical code but still have different references because they are separate function objects.

Example:

const firstFunction = () => {
  console.log("Hello");
};
const secondFunction = () => {
  console.log("Hello");
};
console.log(firstFunction === secondFunction); // false

Although both functions perform the same operation, they are different function objects. This distinction matters when React compares props by reference.

Example inside a React component:

function Parent() {
  const handleClick = () => {
    console.log("Clicked");
  };
  return <Child onClick={handleClick} />;
}

Whenever Parent renders, a new handleClick function is created. If Child is wrapped in React.memo, the changed function reference can cause Child to render again even when the other props remain unchanged.

5. Example Without useCallback

In this example, the parent component contains a counter and passes a function to a child component. Updating the counter creates a new function reference during the next render.

import React, { useState } from "react";
const Child = React.memo(function Child({ onClick }) {
  console.log("Child rendered");
  return (
    <button onClick={onClick}>
      Click Child Button
    </button>
  );
});
function Parent() {
  const [count, setCount] = useState(0);
  const handleClick = () => {
    console.log("Child button clicked");
  };
  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(c => c + 1)}>
        Increase Counter
      </button>
      <Child onClick={handleClick} />
    </div>
  );
}
export default Parent;

Explanation: The Child component is wrapped in React.memo, but the handleClick function gets a new reference whenever Parent renders. React.memo detects that the onClick prop has changed and may render Child again.

6. Using useCallback to Preserve Function References

We can wrap the event handler with useCallback so React can reuse the function reference when its dependencies remain unchanged.

import React, { useCallback, useState } from "react";
const Child = React.memo(function Child({ onClick }) {
  console.log("Child rendered");
  return (
    <button onClick={onClick}>
      Click Child Button
    </button>
  );
});
function Parent() {
  const [count, setCount] = useState(0);
  const handleClick = useCallback(() => {
    console.log("Child button clicked");
  }, []);
  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(c => c + 1)}>
        Increase Counter
      </button>
      <Child onClick={handleClick} />
    </div>
  );
}
export default Parent;

Explanation: The handleClick function has an empty dependency array because it does not use any reactive values from the component. When the counter changes, React can return the same cached handleClick reference. Because the Child component receives the same onClick prop, React.memo can skip its re-render.

Important: The parent component still renders when its counter changes. useCallback does not prevent the parent from rendering; it helps keep the function reference stable.

7. How useCallback Works

The useCallback Hook compares the dependencies from the current render with those from the previous render. React compares each dependency using the Object.is comparison algorithm.

  1. The component renders for the first time.
  2. React receives the function definition and dependency array.
  3. React returns the supplied function and can cache its reference.
  4. The component renders again because of a state or prop update.
  5. React compares the current dependencies with the previous dependencies.
  6. If all dependencies are unchanged, React can return the cached function reference.
  7. If any dependency changes, React returns the function definition from the current render and caches it for possible reuse.

React does not execute the callback function simply because it is passed to useCallback. The function executes when your code calls it, such as when a user clicks a button.

8. Understanding the Dependency Array

The dependency array specifies the reactive values that the callback uses. These values may include props, state variables, and functions or variables declared inside the component.

Example:

const handleMessage = useCallback(() => {
  console.log("Hello, " + name);
}, [name]);

Here, name is included in the dependency array because the callback uses it. If name changes, React provides a new function that uses the updated value.

Common dependency patterns:

Dependency array Meaning
[] The callback has no reactive dependencies, so React can reuse its reference between renders.
[name] The callback reference can remain stable while name is unchanged.
[name, age] The callback reference can remain stable while both name and age are unchanged.
No dependency array A new function is returned on every render, so the Hook does not preserve the callback reference between renders.

9. useCallback with State Variables

A callback may need to read or update a state variable. When the callback reads the current state value, that state variable normally needs to be included in the dependency array.

Example:

import React, { useCallback, useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  const showCount = useCallback(() => {
    console.log("Current count:", count);
  }, [count]);
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(c => c + 1)}>
        Increase
      </button>
      <button onClick={showCount}>
        Show Count in Console
      </button>
    </div>
  );
}
export default Counter;

Explanation: The showCount callback uses count, so count is included in the dependency array. When count changes, React provides an updated callback that reads the latest count value.

10. Updating State with useCallback and Functional Updates

When a callback needs to update state based on its previous value, a functional state update can often avoid including the state variable in the dependency array.

Example:

import React, { useCallback, useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  const increment = useCallback(() => {
    setCount(previousCount => previousCount + 1);
  }, []);
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increment}>
        Increment
      </button>
    </div>
  );
}
export default Counter;

Explanation: The callback does not read count directly. Instead, it passes an updater function to setCount. React supplies the previous state value, so count does not need to be included in the dependency array.

11. useCallback with React.memo

useCallback and React.memo are often used together to optimize rendering performance. React.memo can skip a child's re-render when its props remain shallowly equal. useCallback helps keep callback props stable when their dependencies have not changed.

Example:

import React, { useCallback, useState } from "react";
const SaveButton = React.memo(function SaveButton({ onSave }) {
  console.log("SaveButton rendered");
  return (
    <button onClick={onSave}>
      Save Data
    </button>
  );
});
function App() {
  const [count, setCount] = useState(0);
  const handleSave = useCallback(() => {
    console.log("Data saved successfully");
  }, []);
  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount(c => c + 1)}>
        Increase Counter
      </button>
      <SaveButton onSave={handleSave} />
    </div>
  );
}
export default App;

Explanation: When the counter changes, the parent renders again. Since handleSave retains its reference, SaveButton can skip re-rendering because its onSave prop remains unchanged.

12. useCallback with Event Handlers

Event handlers are functions that respond to user interactions, such as clicking buttons, submitting forms, or changing input fields. useCallback can be useful when these handlers are passed to memoized child components or used as dependencies in other Hooks.

Example:

import React, { useCallback, useState } from "react";
function Form() {
  const [name, setName] = useState("");
  const handleChange = useCallback((event) => {
    setName(event.target.value);
  }, []);
  const handleSubmit = useCallback((event) => {
    event.preventDefault();
    alert("Submitted name: " + name);
  }, [name]);
  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={handleChange}
        placeholder="Enter your name"
      />
      <button type="submit">Submit</button>
    </form>
  );
}
export default Form;

Explanation: handleChange does not read the name variable, so its dependency array can remain empty. handleSubmit reads name, so name is included in its dependency array to ensure that the callback uses the latest value.

13. useCallback with useEffect

A function defined inside a component receives a new reference on each render. If that function is used as a dependency of useEffect, the Effect may run more often than intended.

useCallback can stabilize the function reference when a stable function is genuinely needed. However, when a helper function is only used inside an Effect, defining that helper directly inside the Effect is often simpler.

Example using useCallback:

import React, { useCallback, useEffect } from "react";
function ChatRoom({ roomId }) {
  const createOptions = useCallback(() => {
    return {
      serverUrl: "https://example.com",
      roomId: roomId
    };
  }, [roomId]);
  useEffect(() => {
    const options = createOptions();
    console.log("Connecting with options:", options);
  }, [createOptions]);
  return <h2>Chat Room: {roomId}</h2>;
}
export default ChatRoom;

Explanation: The createOptions function reference changes when roomId changes. The Effect can therefore use createOptions as a dependency without being triggered by an unnecessary new function reference on every unrelated render.

Simpler alternative:

import React, { useEffect } from "react";
function ChatRoom({ roomId }) {
  useEffect(() => {
    function createOptions() {
      return {
        serverUrl: "https://example.com",
        roomId: roomId
      };
    }
    const options = createOptions();
    console.log("Connecting with options:", options);
  }, [roomId]);
  return <h2>Chat Room: {roomId}</h2>;
}
export default ChatRoom;

In this alternative, the helper function is defined inside the Effect, so useCallback is unnecessary. The Effect depends directly on roomId.

14. Difference Between useCallback and useMemo

Both Hooks support memoization, but they cache different things.

Feature useCallback useMemo
Purpose Caches a function definition. Caches the result of a calculation.
Returns A function reference. A calculated value.
Common use Event handlers and callback props. Filtered arrays, sorted data, or expensive calculations.
Example useCallback(() => doSomething(), []) useMemo(() => calculateValue(), [])

Simple rule: Use useCallback when you need to cache a function reference. Use useMemo when you need to cache the result of a calculation.

15. Difference Between useCallback and React.memo

Feature useCallback React.memo
Type React Hook. Higher-order component.
Purpose Can preserve a function reference between renders. Can skip a component render when its props remain shallowly equal.
Applied to Function definitions inside a component or custom Hook. Component definitions.
Example useCallback(handleClick, []) React.memo(Child)

These tools can work together, but neither guarantees that a component will never render. State changes, context changes, and other React behavior can still trigger rendering.

16. When Should You Use useCallback?

  • When passing a callback to a child component wrapped in React.memo.
  • When a function is used as a dependency of another Hook and a stable reference is beneficial.
  • When returning functions from a custom Hook so consumers can optimize their own components.
  • When profiling shows that unstable callback references cause unnecessary rendering work.
  • When maintaining a stable function reference helps avoid unnecessary Effect executions.

17. When Should You Avoid useCallback?

  • When a function is used only in a simple component and there is no performance issue.
  • When the child component is not memoized and a stable callback reference provides no practical benefit.
  • When the callback's dependencies change on every render, making memoization ineffective.
  • When defining the function inside an Effect would be simpler.
  • When adding useCallback makes the code harder to understand without a measurable benefit.

18. Common Mistakes When Using useCallback

  • Missing dependencies: Omitting values used by the callback can cause it to work with outdated values.
  • Using an empty array incorrectly: An empty array is appropriate only when the callback does not need changing reactive values from the component.
  • Expecting it to stop all renders: useCallback stabilizes a function reference; it does not stop the parent component from rendering.
  • Using it everywhere: Memoizing every function can add complexity without improving performance.
  • Changing object dependencies: New object references can cause the callback to be recreated.
  • Calling Hooks conditionally: useCallback must be called at the top level of a component or custom Hook, not inside loops or conditional blocks.
  • Ignoring the Rules of Hooks: Hooks should be called consistently and in the same order on every render.

19. Best Practices for useCallback

  1. Use useCallback when a stable function reference provides a practical benefit.
  2. Include every reactive value referenced inside the callback in the dependency array.
  3. Use functional state updates when updating state based on its previous value.
  4. Combine useCallback with React.memo only when it helps avoid unnecessary child rendering.
  5. Prefer simpler Effect logic when a helper function can be defined inside the Effect.
  6. Use React Developer Tools Profiler to investigate rendering performance.
  7. Keep callback functions pure where practical and avoid unnecessary side effects during rendering.
  8. Remember that useCallback is a performance optimization, not a requirement for correct application behavior.

20. Practical Mini Project: Todo List with useCallback

Objective: Create a Todo List where users can add tasks and remove tasks. Use useCallback to maintain stable event handler references when appropriate.

import React, { useCallback, useState } from "react";
const TodoItem = React.memo(function TodoItem({ todo, onDelete }) {
  console.log("Rendered:", todo.text);
  return (
    <li>
      {todo.text}
      <button onClick={() => onDelete(todo.id)}>
        Delete
      </button>
    </li>
  );
});
function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [task, setTask] = useState("");
  const handleAddTodo = useCallback(() => {
    const trimmedTask = task.trim();
    if (!trimmedTask) return;
    setTodos(previousTodos => [
      ...previousTodos,
      { id: Date.now(), text: trimmedTask }
    ]);
    setTask("");
  }, [task]);
  const handleDeleteTodo = useCallback((id) => {
    setTodos(previousTodos =>
      previousTodos.filter(todo => todo.id !== id)
    );
  }, []);
  return (
    <div>
      <h1>Todo List</h1>
      <input
        value={task}
        onChange={event => setTask(event.target.value)}
        placeholder="Enter a task"
      />
      <button onClick={handleAddTodo}>Add Task</button>
      <ul>
        {todos.map(todo => (
          <TodoItem
            key={todo.id}
            todo={todo}
            onDelete={handleDeleteTodo}
          />
        ))}
      </ul>
    </div>
  );
}
export default TodoApp;

Project explanation:

  • The user enters a task in the input field.
  • handleAddTodo adds the task to the list and depends on task because it reads that state value.
  • handleDeleteTodo removes a task using a functional state update, so it does not need todos as a dependency.
  • TodoItem is wrapped in React.memo and receives a stable onDelete callback.
  • Existing TodoItem components can skip rendering when their todo object and onDelete callback remain unchanged.

Note: The inline onClick wrapper inside each TodoItem is recreated when that TodoItem renders. This does not prevent the parent from benefiting from the stable onDelete callback, but further optimization should be considered only if profiling shows a need.

21. Interview Questions and Answers

Q1. What is useCallback in React?

Answer: useCallback is a React Hook that caches a function definition between renders while its dependencies remain unchanged.

Q2. Why do we use useCallback?

Answer: It helps maintain stable function references, which can prevent unnecessary re-renders of memoized children and unnecessary Hook executions caused by changing function dependencies.

Q3. What is a function reference?

Answer: A function reference identifies a function object in JavaScript. Two functions with identical code can still have different references.

Q4. Does useCallback prevent a component from rendering?

Answer: No. It preserves a function reference when dependencies remain unchanged. React.memo may use that stable reference to skip a child's render.

Q5. What happens when a dependency changes?

Answer: React returns the function definition from the current render and caches it for possible reuse.

Q6. What is the difference between useCallback and useMemo?

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

Q7. Can useCallback be used with React.memo?

Answer: Yes. useCallback can keep callback props stable so React.memo can skip rendering a child when its other props are also unchanged.

Q8. Why is the dependency array important?

Answer: It tells React which reactive values the callback depends on and when a new function reference may be needed.

Q9. Can useCallback update state?

Answer: Yes. A memoized callback can call state setters. Functional updates can help avoid depending on the previous state value directly.

Q10. Should useCallback be used for every function?

Answer: No. It should be used when a stable function reference offers a measurable or practical performance benefit.

22. Summary

The useCallback Hook is an important React optimization technique for caching function definitions between renders. It is especially useful when passing callbacks to memoized child components or when a stable function reference is needed as a Hook dependency. By understanding function references, dependency arrays, functional state updates, and React.memo, developers can use useCallback effectively without adding unnecessary complexity.

23. Learn React JS with JustAcademy

Learn React components, props, state, Hooks, performance optimization, and modern front-end development through structured training and practical projects.

JustAcademy React JS Training

Explore the course and register for a demo session using the link below.

Register for React JS Course Demo

Previous Next
whatsapp