Nearby lessons

24 of 44

🪝 ReactJS – useCallback Hook

📌 What is useCallback?

What is useCallback in React?

The useCallback hook returns a memoized function. It is useful when passing callbacks to child components that rely on reference equality to prevent unnecessary re-renders.

The useCallback and useMemo hooks are similar:

  • useMemo → returns a memoized value.
  • useCallback → returns a memoized function.

📌 Syntax of useCallback

const memoizedFn = useCallback(() => {
  // logic here
}, [dependencies]);

- Callback Function: The function you want to memoize.
- Dependencies: The function is re-created only when dependencies change.

⚙️ Without useCallback

In this example, the Learning function is recreated every time the parent App re-renders. This causes the child component to re-render unnecessarily even if Learning does not change.

React Playground
import React, { useState } from 'react';
import ChildA from './ChildA';

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

  const Learning = () => {
    // some operation
  };

  return (
    <>
      <h1>Learning useCallback</h1>
      <ChildA Learning={Learning} count={count} />
      <h1>{add}</h1>
      <button onClick={() => setAdd(add + 1)}>Addition</button>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 2)}>Count</button>
    </>
  );
}

export default App;

✅ With useCallback

Here, useCallback ensures that Learning function is memoized. It will only re-create if dependencies change, preventing unnecessary child re-renders.

React Playground
import React, { useState, useCallback } from 'react';
import ChildA from './ChildA';

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

  const Learning = useCallback(() => {
    // some operation
  }, []);

  return (
    <>
      <h1>Learning useCallback</h1>
      <ChildA Learning={Learning} count={count} />
      <h1>{add}</h1>
      <button onClick={() => setAdd(add + 1)}>Addition</button>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 2)}>Count</button>
    </>
  );
}

export default App;

🧮 Execution Flow of useCallback

  1. React renders the parent component (App).
  2. The Learning function is created.
  3. If useCallback is used, the same function reference is reused unless dependencies change.
  4. The child component (ChildA) receives props.
  5. Because of React.memo, ChildA only re-renders if props actually change.

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - useMemo Hook