MENU
Avoiding Unnecessary Renders with useCallback
An event handler gets recreated and assigned a different address on every render by default, resulting in a changed 'props' object for the child component. Below, only button 2 is not repeatedly rendered as the 'props' object has not changed. Notice how the entire Example() function runs till completion on every render.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><head>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head><body>
<div></div>
<script type="text/babel">
const MyButton = React.memo(props=>{
console.log('firing from '+props.id);
return (<button onClick={props.eh}>{props.id}</button>);});function Example(){
const [a,setA] = React.useState(0);
const unmemoizedCallback = () => {};
const memoizedCallback = React.useCallback(()=>{},[]); // don’t forget []!
setTimeout(()=>{setA(a=>(a+1));},3000);
return (<React.Fragment>
<MyButton id="1" eh={unmemoizedCallback}/>
<MyButton id="2" eh={memoizedCallback}/>
<MyButton id="3" eh={()=>memoizedCallback}/>
</React.Fragment>);}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Example/>);
</script>
</body></html>useCallback() increases code complexity. It is best reserved for cases where there is a need to avoid rendering 'big' component repeatedly.