useCallback Hook?

useCallback Hook?

In this article, we will learn about useCallback Hook

The React useCallback hook can help you improve the performance of your React apps.

useCallback() hook🪝

The React useCallback Hook returns a memoized callback function.

The useCallback Hook only runs when one of its dependencies update.

The useCallback Hook accepts 2 arguments: a callback function and an array of dependencies. It returns a memoized callback function when any value in the dependency array has changed

what is Referential equality?

Referential equality refers to the comparison of two object references to determine if they point to the same underlying object in memory.

When two object references are compared using referential equality, they are considered equal if and only if they point to the same object in memory. This means that any changes made to one reference will be reflected in the other reference, as they both point to the same object.

Referential equality plays a crucial role in useCallback because it determines whether the memoized function should be re-created or not. The dependencies provided to useCallback are used to compare with the previous dependencies to determine if they have changed.

If the dependencies are referentially equal (i.e., they have the same references), React assumes that the dependencies have not changed and returns the memoized version of the function from the previous render. This avoids re-creating the function and allows React to optimize the rendering process.

On the other hand, if any of the dependencies are not referentially equal (i.e., they have different references), React assumes that the dependencies have changed and recreates the memoized function. This ensures that the latest dependencies are used, and the component can react to the changes appropriately.

The syntax for using useCallback is as follows:

import React, { useCallback } from 'react';

const Component = () => {
  const memoizedCallback = useCallback(() => {
    // callback function logic
  }, [dependency1, dependency2]);

  // Rest of the component logic

  return (
    // JSX rendering using the memoized callback
  );
};

Memoization

The word 'memoized' or 'memoization' is an optimization technique to speed up expensive function calls by returning cached results instead of re-computing if the inputs of the function are the same.

or

Memoization is a way to remember the results of a function for a given set of inputs so that if the function is called again with the same parameters, the cached result can be returned instead of re-computing the function.

Memoization in React is a technique for storing computational results and reusing them.

example demonstrating the use of the useCallback hook in a counter app:

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

const CounterApp = () => {
  const [count, setCount] = useState(0);

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

  const decrement = useCallback(() => {
    setCount((prevCount) => prevCount - 1);
  }, []);

  const reset = useCallback(() => {
    setCount(0);
  }, []);

  return (
    <div>
      <h2>Counter App</h2>
      <h3>Count: {count}</h3>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
};

export default CounterApp;

In this example, we have a Counter app where users can increment, decrement, and reset the count value. The increment, decrement, and reset functions are created using the useCallback hook.

The increment function is memoized using useCallback, with an empty dependency array [], meaning it will always reference the same function instance. This prevents unnecessary re-creation of the function on each render, optimizing performance.

The same memoization process is applied to the decrement and reset functions, ensuring that they don't change on subsequent renders unless their dependencies change.

By utilizing useCallback, the functions maintain their references throughout the component lifecycle, even if the component re-renders. This is particularly useful when passing these functions as props to child components, as it ensures consistent behavior and avoids unnecessary re-renders in child components.

Here's a guideline on when to use useMemo and useCallback hook:

  1. useMemo:

    • Use useMemo when you need to memoize a value, such as the result of a complex computation or a time-consuming operation.

    • Use it when you have a computationally expensive operation that doesn't need to be re-evaluated on every render.

    • Use it to prevent unnecessary re-calculations and improve the performance of your component.

    • Examples: memoizing the result of a selector function, formatting data for display, or caching API responses.

  2. useCallback:

    • Use useCallback when you need to memoize a function, especially when passing it down to child components as a prop.

    • Use it to prevent unnecessary re-creations of functions, which can lead to unnecessary re-renders of child components.

    • Use it when the function relies on external dependencies that may change, and you want to ensure the latest version of the function captures the latest dependencies.

    • Examples: event handlers, callback functions passed to child components, or functions used in the dependency array of other hooks like useEffect.

In summary, use useMemo when you want to memoize a value, and use useCallback when you want to memoize a function