I'm facing an issue with Redux Toolkit where the store resets back to its initial state when I manually type a URL in the browser's address bar (e.g., /admin). However, if I navigate between pages using React Router's component or useNavigate(), the store persists as expected and doesn't reset.
Here's a breakdown of the problem:
When I use React Router Dom to navigate between pages, the Redux store keeps its state. When I manually enter a URL in the browser, the Redux store resets to its initial state. I'm using React with Redux Toolkit for state management and React Router for routing. I would like to persist the Redux store state across page refreshes or manual URL changes.
How can I prevent the Redux store from resetting when I type the URL directly in the browser? Is there a way to make the Redux store persistent when navigating by manually typing the URL or refreshing the page?
How can I prevent the Redux store from resetting when I type the URL directly in the browser? Is there a way to make the Redux store persistent when navigating by manually typing the URL or refreshing the page?
Redux is only an in-memory state management solution, when you manually update the URL in the address bar it's a complete request to the server and page load. The current page is dumped, including any React and Redux state and the entire page is reloaded and React app mounted anew with initial state values.
Use Redux-Persist to persist the Redux store to longer-term storage, i.e. localStorage, and hydrate the store when the app mounts.
The basic setup/example:
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import { Provider } from "react-redux";
import { PersistGate } from 'redux-persist/integration/react';
// ... import reducers ...
const persistConfig = {
key: 'root',
storage,
};
const rootReducer = combineReducers({
// ... reducers ...
});
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = configureStore({
reducer: persistedReducer,
// ...any middlewares and other configuration properties...
});
export const persistor = persistStore(store);
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { persistor, store } from '../path/to/store';
const App = () => {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RootComponent />
</PersistGate>
</Provider>
);
};