reactjsreact-hooks

How can I prevent re-render after state changed in 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?


Solution

  • 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}
    
        </>
     )
    
    }
    

    EDIT:

    Does the <Header/> 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(() => <Header setShowMenu={setShowMenu}/>, [] );