Sunday, 29 September 2024

React Hooks - useMemo

 v useMemo Hook

Ø The React useMemo Hook returns a memoized value.

 

Ø It’s like caching a value so that it doesn't need to be recalculated.

 

Ø The useMemo Hook only runs when one of its dependencies update. This can improve performance.

 

Ø The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function.

 

Ø The useMemo Hook can be used to keep expensive, resource intensive functions from needlessly running.

 

Example: 1 Why we need useMemo Hook (Problem without useMemo Hook)

import React, { useState } from ‘react’

import ‘./App.css’

 

function App() {

           const [number, setNumber] = useState(0)

           const [counter, setCounter] = useState(0)

 

           function cubeNum(num) {

            console.log(‘Calculation done!’);

            return Math.pow(num,3)

}

const  result  = cubeNum(number);

return (

            <>

<input type=”number” value={number} onChange={(e)=>{setNumber(e.target.value)}} />

            <h1>Cube of the number : {result}</h1>

<button onClick={()=>{setCounter(counter+1)}}>

Counter++</button>

<h1>Counter : { counter }</h1>

</>

)

}

export default App; 

so if you are click on Counter++ button then also it will called cubeNum method, because of when we update the counter ,changes the counter number, it re-render web page, it recalculate cube.so to prevent the function to recalculate cube, we can use useMemo hook.



import React, { useState, useMemo } from ‘react’

import ‘./App.css’

 

function App() {

           const [number, setNumber] = useState(0)

           const [counter, setCounter] = useState(0)

 

           function cubeNum(num) {

            console.log(‘Calculation done!’);

            return Math.pow(num,3)

}

//const  result  = useMemo(()=> {return cubeNum(number)},[number]);

const  result  = useMemo(() => cubeNum(number),[number]);

return (

            <>

<input type=”number” value={number} onChange={(e)=>{setNumber(e.target.value)}} />

            <h1>Cube of the number : {result}</h1>

<button onClick={()=>{setCounter(counter+1)}}>

Counter++</button>

<h1>Counter : { counter }</h1>

</>

)

}

export default App;

 

    When click on Counter++ button

    When 3 entered in textbox ,then only called cubeNum method



No comments:

Post a Comment

React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...