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 w3wiki</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:
Performance Hooks in React
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
- useMemo Hook
- useCallback Hooks
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.
Contact Us