useCallback: Hooks in Reactjs

What Is useCallback In React?

useCallback is a hook that returns a memoized callback function which will only change if a dependency changes. In computing, memory allows results to be cached so that they do not need to get recalculated. It helps in boosting performance.

In other words, we can reuse the same function object between renders rather than recreating it each time. You can pass an inline callback and a dependencies array as parameters. If one of the dependencies changes, useCallback returns a memoized version of the callback. Using this method prevents unnecessary renders when calling optimized child components.

Syntax

const memoized = useCallback(() => {
fn()   // the callback function to be memoized
},
Dependency1, Dependency2  // dependencies array
[]);

Parameters

fn

It is the value that you want to memorize for the function. The function can take any argument and return any value. During the initial render, React will return your function to you. As long as the dependencies have not changed since the last render, React will return the same function on subsequent renders. Alternatively, it will store the calling function you passed during the current render so that future renders can reuse it. As a result, React won't call the function. You can decide when and whether to call the returned function.

dependencies

It is an array of all reactive values referenced within a function, such as props, state, variables, and functions declared directly within your component. Whenever you use a React linter, it will verify that reactive values are correctly get defined as dependencies. You should write the list of dependencies inline, like [dep1, dep2, dep3]. React uses the comparison algorithm  "Object.is" to compare each dependency with its previous value.

Coding Example

Without useCallback Hook Example

This example will show how to create a React application with 3 input fields and a function mult to display the multiplication of two numbers.

import React, { useState } from 'react';

const App = () => {
  const [name, setName] = useState('');
  const [num1, setNum1] = useState(0);
  const [num2, setNum2] = useState(0);
  const ans = mult(num1, num2);
  return (
      <div>
        <input
            placeholder="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
        />
        <input
            placeholder="Value 1"
            value={num1}
            onChange={(e) => setNum1(e.target.value)}
        />
        <input
            placeholder="Value 2"
            value={num2}
            onChange={(e) => setNum2(e.target.value)}
        />
        {ans}
      </div>
  );
};

const mult = (a1, a2) => {
  console.log('Multiplying numbers');
  return parseInt(a1) * parseInt(a2);
};

export default App;

write your code here: Coding Playground

Output

As you can see above, regardless of the name entered, the mult function is called every time the application re-renders, making it unoptimized. When the user types, the state changes, causing the app to re-render.

With useCallback Hook Example

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

const App = () => {
  const [name, setName] = useState('');
  const [num1, setNum1] = useState(0);
  const [num2, setNum2] = useState(0);
  const ans = useCallback(() => {
      mult(num1, num2);
  });
  return (
      <div>
        <input
            placeholder="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
        />
        <input
            placeholder="Value 1"
            value={num1}
            onChange={(e) => setNum1(e.target.value)}
        />
        <input
            placeholder="Value 2"
            value={num2}
            onChange={(e) => setNum2(e.target.value)}
        />
        {ans}
      </div>
  );
};
const mult = (a1, a2) => {
  console.log('Multiplying numbers');
  return parseInt(a1) * parseInt(a2);
};
export default App;

write your code here: Coding Playground

Output

This example displays the cached version of the add function, which only updates itself if the a or b values change. If the user types in the name, the function mult is not called.