What is "useCallback()" function usage?

What is "useCallback()" function usage?

In react hook useCallback function used for

useCallbackis a React Hook that memoizes a callback function. It is used to optimize performance by preventing unnecessary re-renders in certain situations. When you use ituseCallback, it memoizes the callback function so that it doesn't get recreated on every render unless its dependencies change.

Here's an example of how to use ituseCallback:

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

const CallbackExample = () => {
  // State to track the count
  const [count, setCount] = useState(0);

  // Callback function without useCallback
  const handleClickWithoutCallback = () => {
    console.log('Button clicked! Count:', count);
    // Do something with the count, but note that this function
    // is recreated on every render.

  // Callback function with useCallback
  const handleClickWithCallback = useCallback(() => {
    console.log('Button clicked! Count:', count);
    // Do something with the count
  }, [count]); // Dependency array: only recreate the function if count changes

  return (
      <p>Count: {count}</p>

      {/* Button without useCallback */}
      <button onClick={handleClickWithoutCallback}>
        Click without useCallback

      {/* Button with useCallback */}
      <button onClick={handleClickWithCallback}>
        Click with useCallback

      {/* Button to update the count */}
      <button onClick={() => setCount(count + 1)}>
        Increment Count

export default CallbackExample;

In this example:

  1. We have a count state variable that we want to use inside a callback function.

  2. handleClickWithoutCallback is a callback function without using useCallback. It gets recreated on every render, which can lead to unnecessary re-renders of components that use this callback.

  3. handleClickWithCallback is a callback function created using useCallback. The second argument to useCallback is an array of dependencies. The callback is only recreated if the dependencies change. In this case, the dependency is count, so the callback is recreated only when count changes.


This is important callback function used for momoizing and stops re-rendering.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!