React useCallback Hook

React‘s useCallback hook is a built-in function that allows you to memoize a function so that it only changes when one of its dependencies changes. This can be useful in optimizing performance by avoiding unnecessary re-renders.

To use useCallback, you first need to create a function that you want to memoize. You then pass this function and an array of dependencies to the useCallback function. The useCallback function will return a memoized version of the function that only changes when one of its dependencies changes.

Here’s an example of how you might use useCallback to memoize a function that calculates the sum of two numbers:

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

function Adder() {
  const [num1, setNum1] = useState(0);
  const [num2, setNum2] = useState(0);

  const sum = useCallback(() => {
    return num1 + num2;
  }, [num1, num2]);

  return (
    <div>
      <p>Num1: {num1}</p>
      <input value={num1} onChange={(e) => setNum1(parseInt(e.target.value))} />
      <p>Num2: {num2}</p>
      <input value={num2} onChange={(e) => setNum2(parseInt(e.target.value))} />
      <p>Sum: {sum()}</p>
    </div>
  );
} 

				
			

In this example, we first declare two state variables num1 and num2, and two setter functions setNum1 and setNum2 using the useState hook.

We then declare a sum function using the useCallback hook. The sum function returns the sum of num1 and num2. We pass num1 and num2 as dependencies to useCallback so that the sum function only changes when num1 or num2 change.

We then render two input elements that allow the user to input num1 and num2, and display the sum of num1 and num2 using the sum function.

By using React’s useCallback hook, we can ensure that the sum function only changes when num1 or num2 change. This can help optimize performance by avoiding unnecessary re-renders.

useCallback is a powerful hook that allows you to memoize functions and optimize performance in functional components. By using it, you can write more efficient and performant code that is easier to understand and maintain.

Join To Get Our Newsletter
Spread the love