'Unnecessary re-render of a component when wanting to add an animation with MUI
I have this component that needs to expand/shrink depending if left drawer is open or closed
This is the code
const MainContent = styled('main', { shouldForwardProp: (prop) => prop !== 'open' })<{
open?: boolean;
}>(({ theme, open }) => ({
background: '#fafafa',
height: 'calc(100vh - 64px)',
overflowX: 'hidden',
flexGrow: 1,
padding: '38px 53px 0px 53px',
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
marginLeft: `-260px`,
...(open && {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginLeft: 0,
}),
}));
const Home = () => {
const isDrawerOpen = useSelector(value);
const isAppSelected = useSelector(value);
return (
<Box style={{ display: 'flex', overflowX: 'hidden' }}>
{/* Main content */}
<MainContent open={isDrawerOpen}>
<>
<SinAsignarHero />
{/* Handeling server errors */}
<RecogidasIssue />
</>
)}
</MainContent>
</Box>
);
};
export default Home;
and, as you can see, MainContent which is a custom component (from MUI) will open/shrink depending on this value that comes from my store (i'm using redux), and it does what it is supposed to do, but, everytime i do that, the other components that live inside MainContent will re-initialize useState, variables and everything, like it somehow is re-rendering the components when isDrawerOpen values changes, i don't want that behavior.
Is it probably that, because of that value, that is changing depending on the user clicking to see/close the left drawer, it will manage to re-render the component ? How can i avoid that ?
Solution 1:[1]
What is happening here, is that, since the value isDrawerOpen is changing constantly, your component is changing as well even though there aren't things changing there directly.
I would suggest you to read this article about how to use React.memo it will help you to avoid unnecessary re-renders when react components are the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

