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(() => { |
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'; |
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'; |
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.