Home > Mobile >  How to prevent re-render after state changed in React Hooks
How to prevent re-render after state changed in React Hooks

Time:11-15

I am new to react hooks. I am trying to build an app but the problem is when I change a state, all the components re-render.

const App=()=>{
   const [showMenu,setshowMenu]=useState(false)
   

 return(
     <>

     <Header showMenu={showMenu} setShowMenu={setShowMenu}/>

     <MainArea/>

     {showMenu ? <Menu/> : null}

     <Footer/>

    </>
 )

}

When I set showMenu to true by button, a menu appears but the problem is all my components (Header,MainArea,Footer) do re-render. I don't want that. How can I solve this problem ? Thank you.

CodePudding user response:

You can use React memo (or PureComponent if you use classes) on the components that you don't want to re-render (MainArea,Footer). This way when an update is forced by their parent they will first make a check if any of their props changed and if not (which is your case), re-render will be skipped.

However it's advisable to perform memoization on expensive components only instead of wrapping everything with React.memo, because memoization also introduces some overhead.

CodePudding user response:

You can use useMemo hook.

It prevents specific jsx contents from rerendering, even when the state that those jsx contents/components use get updated.


const App=()=>{
// you can only memoize parts that do not require use of the updated variable in this case. It means that Header cannot be memoized.

const mainArea = React.useMemo( () => <MainArea/>, [] );

const footer = React.useMemo( () => <Footer/>, [] );

   const [showMenu,setShowMenu]=useState(false)
   

 return(
     <>

     <Header showMenu={showMenu} setShowMenu={setShowMenu}/>

     {mainArea}

     {showMenu ? <Menu/> : null}

     {footer}

    </>
 )

}

Happy coding!


EDIT:

Does the really need the state of the showMenu? Or we can only pass the setShowMenu to it? If so, then you can also memoize the Header component into memo chunk like:

const header = React.useMemo( () => , [] );

  • Related