1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usecallback Hook
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
14Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usecallback Hook

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
14Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useCallback Hook

Overview

In JavaScript, functions are objects. Every time a component re-renders, it creates a brand new function in memory for every event handler (e.g., const handleClick = () => {}).

Usually, this is fine. But if you pass handleClick as a prop down to a child component wrapped in React.memo, you have a problem. React.memo does a shallow comparison of props. Because the parent created a brand new function in memory during the re-render, the child sees a new memory reference, assumes the prop changed, and re-renders anyway!

`useCallback` is a specialized version of useMemo designed specifically for caching functions. It tells React: 'Cache this function definition. Do not create a new function in memory unless the dependencies change.' This allows you to safely pass stable function references down to heavily memoized child components without triggering useless renders.

Syntax

Caching a Function Reference
javascript
import { useState, useCallback, memo } from 'react';

// A highly optimized child component
const MegaButton = memo(function MegaButton({ onClick, children }) {
  console.log("MegaButton Rendered!");
  return <button onClick={onClick}>{children}</button>;
});

function ParentApp() {
  const [text, setText] = useState('');
  const [score, setScore] = useState(0);

  // 1. Without useCallback, this function is rebuilt in memory on every keystroke.
  // MegaButton would re-render endlessly.
  // const handleScore = () => setScore(s => s + 1);

  // 2. With useCallback, the memory reference is locked.
  // MegaButton sees the EXACT same function reference and skips rendering!
  const handleScore = useCallback(() => {
    setScore(s => s + 1);
  }, []); // Empty array = never recreate this function

  return (
    <div>
      <input value={text} onChange={e => setText(e.target.value)} />
      <MegaButton onClick={handleScore}>Add Score</MegaButton>
    </div>
  );
}

Common Pitfalls

  • Stale Closures (Missing Dependencies): If your useCallback function relies on a state variable, but you forget to put it in the dependency array, the cached function will permanently use the initial state value. For example, useCallback(() => console.log(count), []) will always print '0', even if count is currently 100.

Interview Questions

What is the exact difference between useMemo and useCallback?

They are fundamentally the same under the hood. useMemo executes the provided function and caches the result of the function. useCallback caches the function itself, allowing you to pass the unexecuted function reference down to child components safely. In fact, useCallback(fn, deps) is just syntactic sugar for useMemo(() => fn, deps).

When is it actually necessary to use useCallback?

It is only necessary in two scenarios: 1) You are passing the function as a prop to a child component optimized with React.memo. 2) The function is being used as a dependency inside a useEffect array, and you want to prevent the effect from triggering infinitely.

Real-World Example

useCallback with useEffect Dependencies: If you define a function outside a useEffect but use it inside, the ESLint rules will force you to list the function in the dependency array. If you don't wrap the function in useCallback, you will cause an infinite network request loop.

example
javascript
function SearchWidget({ query }) {
  const [results, setResults] = useState([]);

  // The fetch logic is complex, so we abstract it into a function
  // We MUST wrap it in useCallback, because we use it inside useEffect
  const fetchResults = useCallback(async () => {
    const res = await api.search(query);
    setResults(res.data);
  }, [query]); // Recreate this function ONLY when 'query' changes

  useEffect(() => {
    // If fetchResults wasn't wrapped in useCallback, it would be a brand new
    // function every render. This effect would see a 'new' dependency, 
    // re-run the fetch, trigger a render, see a 'new' function, and loop infinitely!
    fetchResults();
  }, [fetchResults]); // The linter forces us to include it here

  return <List items={results} />;
}

Check Your Knowledge

Test your understanding of useCallback Hook with these quick questions.

Question 1

What does the `useCallback` hook actually return?

Question 2

If you pass a normal, un-memoized function as a prop to a child component wrapped in `React.memo`, what happens?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useCallback Hook

Overview

In JavaScript, functions are objects. Every time a component re-renders, it creates a brand new function in memory for every event handler (e.g., const handleClick = () => {}).

Usually, this is fine. But if you pass handleClick as a prop down to a child component wrapped in React.memo, you have a problem. React.memo does a shallow comparison of props. Because the parent created a brand new function in memory during the re-render, the child sees a new memory reference, assumes the prop changed, and re-renders anyway!

`useCallback` is a specialized version of useMemo designed specifically for caching functions. It tells React: 'Cache this function definition. Do not create a new function in memory unless the dependencies change.' This allows you to safely pass stable function references down to heavily memoized child components without triggering useless renders.

Syntax

Caching a Function Reference
javascript
import { useState, useCallback, memo } from 'react';

// A highly optimized child component
const MegaButton = memo(function MegaButton({ onClick, children }) {
  console.log("MegaButton Rendered!");
  return <button onClick={onClick}>{children}</button>;
});

function ParentApp() {
  const [text, setText] = useState('');
  const [score, setScore] = useState(0);

  // 1. Without useCallback, this function is rebuilt in memory on every keystroke.
  // MegaButton would re-render endlessly.
  // const handleScore = () => setScore(s => s + 1);

  // 2. With useCallback, the memory reference is locked.
  // MegaButton sees the EXACT same function reference and skips rendering!
  const handleScore = useCallback(() => {
    setScore(s => s + 1);
  }, []); // Empty array = never recreate this function

  return (
    <div>
      <input value={text} onChange={e => setText(e.target.value)} />
      <MegaButton onClick={handleScore}>Add Score</MegaButton>
    </div>
  );
}

Common Pitfalls

  • Stale Closures (Missing Dependencies): If your useCallback function relies on a state variable, but you forget to put it in the dependency array, the cached function will permanently use the initial state value. For example, useCallback(() => console.log(count), []) will always print '0', even if count is currently 100.

Interview Questions

What is the exact difference between useMemo and useCallback?

They are fundamentally the same under the hood. useMemo executes the provided function and caches the result of the function. useCallback caches the function itself, allowing you to pass the unexecuted function reference down to child components safely. In fact, useCallback(fn, deps) is just syntactic sugar for useMemo(() => fn, deps).

When is it actually necessary to use useCallback?

It is only necessary in two scenarios: 1) You are passing the function as a prop to a child component optimized with React.memo. 2) The function is being used as a dependency inside a useEffect array, and you want to prevent the effect from triggering infinitely.

Real-World Example

useCallback with useEffect Dependencies: If you define a function outside a useEffect but use it inside, the ESLint rules will force you to list the function in the dependency array. If you don't wrap the function in useCallback, you will cause an infinite network request loop.

example
javascript
function SearchWidget({ query }) {
  const [results, setResults] = useState([]);

  // The fetch logic is complex, so we abstract it into a function
  // We MUST wrap it in useCallback, because we use it inside useEffect
  const fetchResults = useCallback(async () => {
    const res = await api.search(query);
    setResults(res.data);
  }, [query]); // Recreate this function ONLY when 'query' changes

  useEffect(() => {
    // If fetchResults wasn't wrapped in useCallback, it would be a brand new
    // function every render. This effect would see a 'new' dependency, 
    // re-run the fetch, trigger a render, see a 'new' function, and loop infinitely!
    fetchResults();
  }, [fetchResults]); // The linter forces us to include it here

  return <List items={results} />;
}

Check Your Knowledge

Test your understanding of useCallback Hook with these quick questions.

Question 1

What does the `useCallback` hook actually return?

Question 2

If you pass a normal, un-memoized function as a prop to a child component wrapped in `React.memo`, what happens?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A