Reputation: 79
I have a page in my app with a sidebar menu and a content section. The content for each menu option is dynamically generated using api calls. With my current implementation, every time an option in the menu is selected, it will rerender/regenerate the content for that option, which takes a couple of seconds due to the api calls. What is the best approach to have all the content components rendered only once, and then reused every time the menu option for that section is selected?
function ProjectDashboard(props: sciOpsProps) {
const menuItems = [
{
key: "monitor_progress",
label: "Monitor Progress"
},
{
key: "setup_experiment",
label: "Setup Experiment"
},
{
key: "define_subject",
label: "Define Subject"
},
{
key: "record_session",
label: "Record Session"
},
{
key: "analyze_results",
label: "Analyze Results"
}
]
const menuMap: { [key: string]: ReactElement } = {
monitor_progress: <ProgressSection token={props.token} />,
setup_experiment: <ExperimentSection token={props.token} />,
define_subject: <SubjectsSection token={props.token} />,
record_session: <SessionsSection token={props.token} />,
analyze_results: <ResultsSection token={props.token} />
}
const [content, setContent] = useState<ReactElement>(menuMap["monitor_progress"])
const handleSelect = (key: string) => {
setContent(menuMap[key])
}
return (
<Row>
<Col span={3}>
<Menu
onSelect={(menuItem) => handleSelect(menuItem.key)}
items={menuItems}
defaultSelectedKeys={["monitor_progress"]}
/>
</Col>
<Col span={21}>
{content}
</Col>
</Row>
)
}
Upvotes: 0
Views: 356
Reputation: 686
This is a very common problem in React or any other frontend framework. Luckily the solution is plenty as well.
React Query handles all of the caching and revalidation for you. Each API call will be a query, each of your component can reference the query. Your data will be fetched once and cached, then each of your components can react to the update as needed.
Upvotes: 1