Open In App

Performance Hooks in React

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

While developing React Applications, optimizing performance is one of the most important things for delivering a seamless user experience. One common way to boost performance is to minimize unnecessary re-renders by skipping repetitive calculations. React provides two powerful hooks, useMemo and useCallback, which helps you to achieve optimization by caching results and function definitions, respectively. In this article, we’ll learn about the functionalities of these hooks and explore how they can be effectively utilized to enhance React application performance.

We will discuss about the following Performance Hooks in React:

Table of Content

Both useMemo and useCallback are part of React’s hooks API introduced in React 16.8. While they serve different purposes, they share a common goal of optimizing performance by memoizing values and functions.

useMemo Hook

In React useMemo Hook returns a memoized value and prevents the application from unnecessary re-renders. It is useful in heavy computations and processes when using functional components.

Syntax:

const memoizedValue = useMemo(functionThatReturnsValue, arrayDependencies)

Example: In this example, we have used the number as the squareNum will run only when the number changes. If we increase the counter and the number remains the same in the input field the squareNum doesn’t run again.

Javascript




// Filename - App.js
 
import React, { useState, useMemo } from "react";
 
function App() {
    const [number, setNumber] = useState(0);
    // Using useMemo
    const squaredNum = useMemo(() => {
        return squareNum(number);
    }, [number]);
    const [counter, setCounter] = useState(0);
 
    // Change the state to the input
    const onChangeHandler = (e) => {
        setNumber(e.target.value);
    };
 
    // Increases the counter by 1
    const counterHander = () => {
        setCounter(counter + 1);
    };
    return (
        <div style={{marginLeft: "20%"}}>
            <h1>Welcome to Geeksforgeeks</h1>
            <input
                type="number"
                placeholder="Enter a number"
                value={number}
                onChange={onChangeHandler}>
            </input>
 
            <div>OUTPUT: {squaredNum}</div>
            <button onClick={counterHander}>
                Counter ++
            </button>
            <div>Counter : {counter}</div>
        </div>
    );
}
 
// Function to square the value
function squareNum(number) {
    console.log("Squaring will be done!");
    return Math.pow(number, 2);
}
 
export default App;


Output:

Animation34

useCallback Hooks

The useCallback hook is used when you have a component in which the child is rerendering again and again without need.

Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

Syntax:

const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);

Example: When we change the state ‘count’ then two functions will re-instantiated so the set size will increase by 2 and when we update the state ‘number’ then only one function will re-instantiated and the size of the set will increase by only one.

Javascript




import React, { useState, useCallback } from 'react'
var funccount = new Set();
const App = () => {
 
    const [count, setCount] = useState(0)
    const [number, setNumber] = useState(0)
 
    const incrementCounter = useCallback(() => {
        setCount(count + 1)
    }, [count])
    const decrementCounter = useCallback(() => {
        setCount(count - 1)
    }, [count])
    const incrementNumber = useCallback(() => {
        setNumber(number + 1)
    }, [number])
 
    funccount.add(incrementCounter);
    funccount.add(decrementCounter);
    funccount.add(incrementNumber);
    alert(funccount.size);
 
    return (
        <div>
            Count: {count}
            <button onClick={incrementCounter}>
                Increase counter
            </button>
            <button onClick={decrementCounter}>
                Decrease Counter
            </button>
            <button onClick={incrementNumber}>
                increase number
            </button>
        </div>
    )
}
 
export default App;


Output:

Lightbox



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads