How can I maintain state in React routes to prevent unmounting when switching between them? In my application, it's crucial to keep the state intact during route changes.
When changing routes, the respective components mount and unmount. How can this be prevented?
I've searched through:
How can I prevent the unmount in React Components?
How can I prevent React from unmounting/remounting a component?
However, none of the solutions seem to work for me.
index.js
import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import App from "./App";
import First from "./routes/First";
import Second from "./routes/Second";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<BrowserRouter>
<Routes>
<Route path="" element={<App />} />
<Route path="first" element={<First />} />
<Route path="second" element={<Second />} />
</Routes>
</BrowserRouter>
);
App.js
import * as React from "react";
import { Link } from "react-router-dom";
export default function App() {
return (
<div>
<h1>Prevent Routing</h1>
<nav
style={{
borderBottom: "solid 1px",
paddingBottom: "1rem"
}}
>
<Link to="/first">First</Link> |<Link to="/second">Second</Link>
</nav>
</div>
);
}
First.js
import * as React from "react";
import { useEffect } from "react";
import { Link } from "react-router-dom";
export default function First() {
useEffect(() => {
console.log("mounted First");
return () => console.log("unmounted First");
}, []);
return (
<main style={{ padding: "1rem 0" }}>
<Link to="/">Home</Link>
<h2>First</h2>
</main>
);
}
Second.js
import * as React from "react";
import { useEffect } from "react";
import { Link } from "react-router-dom";
export default function Second() {
useEffect(() => {
console.log("mounted Second");
return () => console.log("unmounted Second");
}, []);
return (
<main style={{ padding: "1rem 0" }}>
<Link to="/">Home</Link>
<h2>Second</h2>
</main>
);
}