useCallback

what is useCallback() ?

  • Profile picture of Mcs
  • by Mcs July 3, 2025

useCallback() is a React Hook used to memoize functions, so they are not re-created on every re-render unless necessary.

Why Use useCallback()?

In React, functions are recreated every time a component renders.
This can cause problems like:

  1. Unnecessary re-renders in child components
  2. Loss of performance with heavy operations

đź”§ useCallback() solves this by caching the function until its dependencies change.

Syntax

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

  1. memoizedFn: returns the same function instance unless dependencies change.
  2. dependencies: array of values the function depends on.

Example Without useCallback() (causes extra re-renders)

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

 const handleClick = () => {
   console.log('Clicked');
 };

 return (
   <>
     <button onClick={() => setCount(count + 1)}>+1</button>
     <Child onClick={handleClick} />
   </>
 );
}

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

Every time Parent re-renders, handleClick is recreated → Child also re-renders.

Example With useCallback() (prevents extra re-render)

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

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

 const handleClick = useCallback(() => {
   console.log('Clicked');
 }, []); // memoized function

 return (
   <>
     <button onClick={() => setCount(count + 1)}>+1</button>
     <Child onClick={handleClick} />
   </>
 );
}

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

Now Child won’t re-render unless handleClick actually changes.

Summary

FeatureDescription
useCallback()Memoizes a function
PreventsRecreating the same function on every render
Useful withReact.memo, performance-heavy functions
ReturnsA memoized version of the callback function

Common Use Cases

  1. Passing callbacks to memoized child components
  2. Preventing re-renders in large component trees
  3. Performance optimization in lists, charts, or animations

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.