1
votes

I'm new to react-router-dom, and I'm trying to create a tabs menu, with a different route for each tab. I'm trying to keep the tabs state persistent between tabs switching by keeping the hidden tabs mounted. How can I achieve this? React router remounts each component every time the route switches even when using the render prop as per the docs.

My contact component has an internal state, and when I navigate to another tab, it's unmounted so the state is lost

      <Route path={`${path}`} exact render={() => <Home />} />
      <Route path={`${path}/profile`} render={() => <Profile />} />
      <Route path={`${path}/contact`} render={() => <Contact />} />

Here is a codesandbox for the example : https://codesandbox.io/s/gallant-lake-vhdby?file=/src/App.js

1

1 Answers

0
votes

You can maintain the state in localStorage upon unmount and repopulate it in initialState

const Contact = () => {
  const [count, setCount] = useState(JSON.parse(localStorage.getItem("count")));

  useEffect(() => {
    return () => {
      console.log("unmounted");
    };
  });

  useEffect(() => {
    console.log("mounted");
    return () => {
      localStorage.setItem("count", count);
    };
  }, [count]);
  return (
    <div onClick={() => setCount(prevCount => prevCount + 1)}>
      You're on the Contact Tab. You pressed me {count} times
    </div>
  );
};

Another solution is to not maintain state in contact component but in App component and pass it on to Contact as props

<Route path={`${path}/contact`} render={(routerProps) => <Contact {...routeProps} count={count} setCount={setCount}/>} />