Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 585
C D Avatar asked Dec 06 '25 07:12

C D


2 Answers

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}/>, [] );
like image 94
Mila A Avatar answered Dec 08 '25 21:12

Mila A


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.

like image 39
fgkolf Avatar answered Dec 08 '25 21:12

fgkolf