What is useCallback and how does it optimize performance?

useCallback returns a memoized version of a callback function that only changes if one of its dependencies has changed.

The Problem it Solves:

In React, every time a component re-renders, all functions declared inside it are re-created. While this is fast and usually not a problem, it becomes a severe performance issue if you pass these functions as props to tightly-optimized child components (components wrapped in React.memo). Because the function reference is new, React.memo thinks the props have changed and forces the child to re-render, defeating the purpose of the optimization.

How useCallback fixes it:

By wrapping the function in useCallback(fn, deps), React caches the function instance. On subsequent renders, React returns the exact same cached function as long as the dependencies haven't changed, preserving referential equality and allowing React.memo to skip unnecessary child renders.

Code example

tsx
1import React, { useState, useCallback, memo } from 'react';
2
3// Heavily optimized child component
4const ExpensiveChart = memo(function ExpensiveChart({ data, onDataPointClick }) {
5 console.log("ExpensiveChart rendered! (Imagine this takes 500ms)");
6
7 return (
8 <div className="p-4 bg-slate-100 rounded-lg mt-4">
9 <h3 className="font-bold">Complex Chart</h3>
10 <button
11 onClick={() => onDataPointClick('Point A')}
12 className="mt-2 bg-slate-300 px-3 py-1 rounded"
13 >
14 Click Data Point
15 </button>
16 </div>
17 );
18});
19
20export default function Dashboard() {
21 const [count, setCount] = useState(0);
22 const [chartData] = useState([1, 2, 3]); // Static for example
23
24 // ✅ Without useCallback, this function is re-created on every 'count' update,
25 // breaking the ExpensiveChart's memoization and causing lag.
26 // With useCallback, the reference stays exactly the same.
27 const handleChartClick = useCallback((point) => {
28 console.log(`Clicked on ${point}`);
29 // Note: If this function used 'count', it MUST be in the dependency array!
30 }, []);
31
32 return (
33 <div className="p-6 border rounded-xl">
34 <h2 className="text-2xl mb-4">Counter: {count}</h2>
35 <button
36 onClick={() => setCount(c => c + 1)}
37 className="bg-blue-600 text-white px-4 py-2 rounded"
38 >
39 Update Counter (Fast)
40 </button>
41
42 {/* This chart will NOT re-render when count changes! */}
43 <ExpensiveChart
44 data={chartData}
45 onDataPointClick={handleChartClick}
46 />
47 </div>
48 );
49}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.

Open in study app