Wednesday, November 2, 2022

React: Usecallback & usememo--To improve performance


  

v:157: usecallback

use it when required instead of running every time. 

(instead of running all the states,or all data in function, we can control it with usecallback, triggered only when requeired, check below code, 2 buttons added first click on paragraph button tht doesnt work, when clicking on first buttong and then clik on 2nd it works and it triggers, check with console)

function App(){

const [showParagraph, setShowParagraph]=useState(false);

const [allowToggle, setAllowToggle]=useState(false);


const toggleParagraphHandler=useCallback(()=>{

if(allowToggle){

setShowParagraph((prevShowParagraph)=>!prevShowParagraph);

}

},[allowToggle]);


const allowToggleHandler=()=>{

setAllowToggle(true);

}


return <Fragment>

<Button onClick="allowToggleHandler">Allow Toggling</Button>

<Button onClick="toggleParagraphHandler">Toggle Paragraph</Button>

</Fragment>

}

No comments:

Post a Comment