Is there a way to keep the state of the tab in React?

Viewed 2149

I use react-router-dom to navigate between tabs in ReactJS project.

In the App component I have:

...
 <Navbar collapseOnSelect id="topBar" bg="white" variant="light" sticky='top' expand="xl">
                    <Navbar.Brand href="/"></Navbar.Brand>
                    <Navbar.Toggle aria-controls="basic-navbar-nav"/>
                    <Navbar.Collapse>
                        <Nav justify className="textFontTabs textBig mr-auto" variant="tabs" defaultActiveKey="/"
                             activeKey={history.location.pathname}>
                            {tabs.map(tab =>
                                (<Nav.Link as={Link} key={tab.name} to={tab.pathname}>{tab.name}</Nav.Link>))
                            }
                        </Nav>
                    </Navbar.Collapse>
                </Navbar>
            </>
            <Switch>
                <Route exact path="/" render={() => <Home/>}/>
                <Route path="/configurator" render={() =>
                    <Configurator contentHeight={contentHeight}/>}/>
            </Switch>
...

My problem is that I have most of the data in the Configurator component stored in state hooks and when I change the tab, for example for Home, and come back to Configurator again, all the data I stored there is set to default. Is there a way to remember the data in Configurator? I've found out that I can use react-redux, but I think it's too small project to use it.

2 Answers

One approach would be to lift your state up. The React docs go into examples.

The idea is that instead of having the Configurator component owning the state, the state is instead kept in the parent component. Configurator gets all the data it needs to display from props and uses delegates to let the parent know when values change.

If it doesn't make sense for the parent component to keep the state, then you might consider persisting the state elsewhere like to the server or use local storage.

Nope. When you change routes, the Configurator component unmounts, and it does not remember the state variable values. You will need to think of a more global state management system. React-redux is great, but if you feel the project is too small, you may be fine just keeping all those state variables and setters in whatever component is rendering Navbar, and passing them as props to Configurator. Or you can use a react context object to offload that state. But with the way you have it set up right now, state will not persist through rerenders.

Related