I am using React and Material UI v5. I have a menu component inside my layout that has children. When clicking on the menu it causes the children to refresh. I have tried solving it by wrapping the children components in React.memo(child) but the result is still the same. What am I doing wrong?
menu component
const MyMenu = ({ menuAnchorEl, setMenuAnchorEl }) => {
const menuOpen = Boolean(menuAnchorEl);
const handleMenuClose = () => {
setMenuAnchorEl(null);
};
const menuOptions = [
{
link: '/overview',
Icon: Dashboard,
label: 'Overview',
},
];
const MenuOption = ({
link,
Icon,
label,
}: {
link: string;
Icon: OverridableComponent<SvgIconTypeMap<unknown, 'svg'>> & {
muiName: string;
};
label: string;
}) => {
return (
<NavLink href={link}>
<MenuItem>
<ListItemIcon>
<Icon color="secondary" fontSize="small" />
</ListItemIcon>
<ListItemText sx={{ color: 'text.primary' }}>
{label}
</ListItemText>
<Typography variant="body2"></Typography>
</MenuItem>
</NavLink>
);
};
return (
<Menu
anchorEl={menuAnchorEl}
open={menuOpen}
onClose={handleMenuClose}
variant="selectedMenu"
>
<MenuList>
{menuOptions.map((n) => (
<MenuOption key={n.link} {...n} />
))}
</MenuList>
</Menu>
);
};
layout component
const MyLayout = observer(({ children }: IProps) => {
const classes = useStyles();
const [menuAnchorEl, setMenuAnchorEl] = React.useState<null | HTMLElement>(
null,
);
return (
<>
<Hidden mdDown implementation="css">
<InstallerMenu
menuAnchorEl={menuAnchorEl}
setMenuAnchorEl={setMenuAnchorEl}
/>
<div className={classes.appFrame}>
<div className={classes.container}>{children}</div>
</div>
</Hidden>
</>
);
});
You have the MenuOption Component inside MyMenu and each time react re-render the main component MyMenu the MenuOption get re defined and cause all the children's to re-render again, in order to fix the issue you must take the MenuOption outside the main components and pass the required props to it, your code will look like this
alos read this article to know more why component inside component is bad
const MyMenu = ({ menuAnchorEl, setMenuAnchorEl }) => {
const menuOpen = Boolean(menuAnchorEl);
const handleMenuClose = () => {
setMenuAnchorEl(null);
};
const menuOptions = [
{
link: '/overview',
Icon: Dashboard,
label: 'Overview',
},
];
return (
<Menu
anchorEl={menuAnchorEl}
open={menuOpen}
onClose={handleMenuClose}
variant="selectedMenu"
>
<MenuList>
{menuOptions.map((n) => (
<MenuOption key={n.link} {...n} />
))}
</MenuList>
</Menu>
);
};
function MenuOption({requiredProps}){
return (
<NavLink href={link}>
<MenuItem>
<ListItemIcon>
<Icon color="secondary" fontSize="small" />
</ListItemIcon>
<ListItemText sx={{ color: 'text.primary' }}>
{label}
</ListItemText>
<Typography variant="body2"></Typography>
</MenuItem>
</NavLink>
);
};