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;
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;
Ø
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>
</>
)
}
No comments:
Post a Comment