Sunday, 6 October 2024

React Hooks - useCallback

 v useCallback Hook

Ø useCallback is a react hook that lets you a catch a function definition between re-renders.

Ø It means when we use the useCallback Hook, it doesn’t create multiple instance of same function when re-render happens.

Ø Instead of creating new instance of  the function, it provides  the cached function on re-render  of the component.

Ø useCallback hook returns a memoized callback function.

Ø Think of memoization as caching a value so that it does not need to be recalculated.

Ø The useCallback Hook only runs when one of its dependencies update.

Ø One reason to use useCallback is to prevent a component from re-rendering unless its props have changed.

 

Example -1 :

Step:1 Add below code in App component

 

import React, {useState} from ‘react’;

import ‘./App.css’;

import Header from ‘./components/Header’;

 

function App() {

           const [count, setCount] = useState(0);

return (

            <>

            <Header />

<h1>{count}</h1>

<button onClick={()=>setCount(prev=>prev+1)}>Click Here</button>

</>

)

}

export default App;

 

Step:2 Create new component under src/components/Header.js and add below code.

 

import React from ‘react’;

const Header =() => {

           console.log(“Header Rendered”);

return (

            <>

<h2>Header</h2>

</>

)

}

export default Header;


When render first time then Header component is render



Ø When click on button then also render Header component as seen in console.















Ø To restrict component rendering on button click use useMemo in Header component

 

import React from ‘react’;

const Header =() => {

           console.log(“Header Rendered”);

return (

            <>

<h2>Header</h2>

</>

)

}

export default React.memo(Header);

 

Step: 3 Add new function in App component, pass this function as props in Header Component.

 

import React, {useState} from ‘react’;

import ‘./App.css’;

import Header from ‘./components/Header’;

 

function App() {

           const [count, setCount] = useState(0);

           const  newFn = () => {}

return (

            <>

            <Header newFn={newFn} />

<h1>{count}</h1>

<button onClick={()=>setCount(prev=>prev+1)}>Click Here</button>

</>

)

}

export default App;

 

It will again render Header function, which is not required because we are not changing anything in Header component, and it is happen because referential equality.


Ø So as in below example in console two have same function returning value but when compare it gives false this is because both function located at different memory location.so both are not same function. So in same way when re-render components, it’s create new instance of this function.so every time we passing function as a prop as a new function.so props are changing that’s reason it will re-render Header component.

 

So here when we click on button that’s update count, so it’s state is changing and it will re-render App component, so when App component re-render it will again create new instance of newFn, which will mouting in Header component.so in Header component in every render we are passing new function which is different.so now we can solve by using useCallback Hook.





Ø To use useCallback hook

Step 3 update below code in App component.

 

Here, useCallback will not create another function, it will use the cached function. whenever it will create the function first time & it will catch that function in the memory and whenever  re-renders happen it will use that cached function, so the function will be the same and when function will be same, then header function props is same , so there is no change in props, so when props is not changing header will not re-render. Header component renders only once.

 

import React, {useCallback, useState} from ‘react’;

import ‘./App.css’;

import Header from ‘./components/Header’;

 

function App() {

           const [count, setCount] = useState(0);

           const  newFn = useCallback(()=>{},[])

return (

            <>

            <Header newFn={newFn} />

<h1>{count}</h1>

<button onClick={()=>setCount(prev=>prev+1)}>Click Here</button>

</>

)

}

export default App;


Ø If you want to call function when count is changed, then update below line

        const  newFn = useCallback((count)=>{},[count])




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 ...