'How to optimize component rendering?
How to optimize component rendering?
I have routes, depending on which the content of the sidebar changes, but there are places where the route is different, and the content of the sidebar does not change, how to make sure that in this case the sidebar does not re-render?
{
path: '/users',
exact: true,
breadcrumb: DynamicBreadcrumb,
sidebar: () => <SidebarComponents.Users/>, // 1
main: () => <Modules.Users/>,
},
{
path: '/users/:id/settings',
exact: true,
breadcrumb: DynamicBreadcrumb,
sidebar: () => <SidebarComponents.Users/>, // 2
main: () => <Modules.UsersSettings/>,
},
{
path: '/users/:id',
exact: true,
breadcrumb: DynamicBreadcrumb,
sidebar: () => <SidebarComponents.SelectedUser/>,
main: () => <Modules.SelectedUser/>,
},
{routes.map((route, idx) => (
<Route key={idx} path={route.path} exact={route.exact}>
<Wrapper>
<Sidebar component={<route.sidebar />} /> // Now every time the route changes, the sidebar is re-rendered
<>
<Modules.Header />
<Breadcrumbs />
<route.main />
</>
</Wrapper>
</Route>
))}
Solution 1:[1]
If I'm reading your code and understanding the issue correctly I believe this rerendering is caused by using an anonymous function to render the sidebar component instead of passing a direct reference to a React component.
Example:
[
{
path: '/users',
exact: true,
breadcrumb: DynamicBreadcrumb,
sidebar: SidebarComponents.Users, // 1
main: () => <Modules.Users/>,
},
{
path: '/users/:id/settings',
exact: true,
breadcrumb: DynamicBreadcrumb,
sidebar: SidebarComponents.Users, // 2
main: () => <Modules.UsersSettings/>,
},
{
path: '/users/:id',
exact: true,
breadcrumb: DynamicBreadcrumb,
sidebar: SidebarComponents.SelectedUser,
main: () => <Modules.SelectedUser/>,
},
]
...
{routes.map(({ exact, path, sidebar }) => (
<Route key={path} path={path} exact={exact}>
<Wrapper>
<Sidebar component={sidebar} /> // <-- pass as reference
<>
<Modules.Header />
<Breadcrumbs />
<route.main />
</>
</Wrapper>
</Route>
))}
...
In Sidebar rename the component prop to Component and render as JSX.
const Sidebar = ({ ...other props ..., component: Component }) => {
...
return (
...
<Component />
...
);
}
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 | Drew Reese |
