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?
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}
</>
)
}
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}/>, [] );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With