I'm developing a React TypeScript application where I've implemented tabbed content, similar to a browser. Each tab contains a component, and I've encountered an issue where switching tabs causes the components to restart, leading to loss of data in forms, open modals, etc. These components are stored in a list of objects. How can I ensure that switching tabs doesn't cause the component to restart, thus preserving the data within it?
Here's what I've tried so far:
- Initially, I stored the components directly in an array of objects and rendered them based on the active tab index.
- I also experimented with React Router and conditional rendering, but couldn't prevent the component from reinitializing when switching tabs.
interface MainContentTab {
id: string;
title: string;
content: JSX.Element;
history: JSX.Element[];
icon?: JSX.Element;
state?: any;
}
...
export const useTabs = () => {
return useContext(TabsContext);
};
export const TabsProvider = ({ children }: { children: ReactNode }) => {
const [tabs, setTabs] = useState<MainContentTab[]>([]);
const [activeTab, setActiveTab] = useState<string>("");
...
return (
<TabsContext.Provider value={{ tabs, addTab, ... }}> {children} </TabsContext.Provider>
);
};
const MainContentTabs = () => {
return (<>
<Box
component="main"
className="MainContent"
... />
{/* solution proposed from Alex Wayne,
it works but I really want to save the state,
maby for refreshing the site? */}
{tabs.map((tab, index) => (
<Box sx={{ display: (tab.id === activeTab) ? "block" : "none" }}>
{tab.content || null}
</Box>
))}
{/* Old solution */}
{/* {tabs.find(tab => tab.id === activeTab)?.content || null} */}
</Box>
{contextMenuPos && (
<TabsContextMenu
tabId={contextMenuTabId}
x={contextMenuPos.x}
y={contextMenuPos.y}
onClose={handleCloseContextMenu} />
)}
</>);
};
This image shows the old solution, but I want a more solution that saves the component render status:

What I was expecting:
- I expected the components to retain their state and not reinitialize when switching tabs, similar to how browsers preserve the state of opened tabs.