DEV Community

Cover image for Simplifying React Hooks: useCallback ๐Ÿ’ฏ
Ali Samir
Ali Samir

Posted on

2

Simplifying React Hooks: useCallback ๐Ÿ’ฏ

Introduction

React provides several powerful hooks to manage state and performance optimizations. One such hook is useCallback, which prevents unnecessary re-renders in functional components.

In this article, we will explore useCallback in-depth, understand its benefits, and learn how to use it effectively with TypeScript.


What is useCallback?

The useCallback hook is a built-in React hook that returns a memoized version of a callback function. It prevents tasks from being recreated unless one of their dependencies changes.

This is particularly useful when passing functions as props to child components.

Syntax

const memoizedCallback = useCallback(
  () => {
    // function logic
  },
  [dependencies] // Dependencies array
);
Enter fullscreen mode Exit fullscreen mode

Why Use useCallback?

Using useCallback helps optimize performance by ensuring that functions do not get recreated on every render. This is especially useful when:

  • Passing functions as props to memoized child components.

  • Preventing unnecessary re-renders caused by function identity changes.

  • Improving performance in large-scale applications.


Example 1: Basic Usage

Let's look at a simple example of how useCallback prevents unnecessary re-renders.

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

type ButtonProps = {
  handleClick: () => void;
};

const Button: React.FC<ButtonProps> = ({ handleClick }) => {
  console.log("Button component re-rendered");
  return <button onClick={handleClick}>Click Me</button>;
};

const MemoizedButton = React.memo(Button);

const App: React.FC = () => {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prev) => prev + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <MemoizedButton handleClick={increment} />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The Button component is memoized using React.memo, so it only re-renders when its props change.

  • The increment function is wrapped in useCallback, ensuring that its reference remains stable unless its dependencies change.

  • This prevents unnecessary re-renders of the MemoizedButton component.


Example 2: useCallback with Dependencies

If a function relies on external state or props, it should include them in the dependencies array.

const incrementByValue = useCallback(
  (value: number) => {
    setCount((prev) => prev + value);
  },
  [setCount]
);
Enter fullscreen mode Exit fullscreen mode

This ensures that whenever setCount changes, the function reference updates accordingly.


When Not to Use useCallback

While useCallback is useful, overusing it can lead to unnecessary complexity. Avoid using it when:

  • The function does not cause re-renders in child components.

  • The function is not passed as a prop.

  • Performance improvements are negligible.


Conclusion

useCallback is a powerful hook that helps optimize performance in React applications by memoizing function references.

When used correctly with TypeScript, it enhances both performance and maintainability. However, it should be used wisely to avoid premature optimization.


๐ŸŒ Connect With Me On:

๐Ÿ“ LinkedIn
๐Ÿ“ X (Twitter)
๐Ÿ“ Telegram
๐Ÿ“ Instagram

Happy Coding!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay