How To Use useCallback Hook In React? See Example

What Is useCallback Hook?

The useCallback hook memoizes a function so that it is not recreated on every render. It’s useful when passing functions to memoized child components to avoid unnecessary re-renders.


Basic Syntax

const memoizedCallback = useCallback(() => {
  // function logic
}, [dependencies]);
  • memoizedCallback → memoized function
  • dependencies → array controlling when function updates

Example

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

const Child = React.memo(({ handleClick }) => {
  console.log("Child rendered");
  return <button onClick={handleClick}>Click Me</button>;
});

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

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

  return (
    <div>
      <Child handleClick={handleClick} />
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <p>Count: {count}</p>
    </div>
  );
}

✅ Child does not re-render when count changes because handleClick is memoized.


Key Points

  • Memoizes functions in functional components
  • Prevents unnecessary re-renders of memoized children
  • Works with dependencies to update function when needed
  • Combine with React.memo for optimal performance

Conclusion

useCallback is essential for optimizing React apps, reducing re-renders, and improving performance when passing functions as props.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *