Persisting State with Redux Persist in Redux v5.0.0
Demonstrate the implementation of redux-persist in a Redux v5.0.0 store to persist and rehydrate state across sessions.
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
// Your root reducer
import rootReducer from './reducers';
const persistConfig = {
key: 'root',
storage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
// Create a store with the persisted reducer
export const store = createStore(persistedReducer);
export const persistor = persistStore(store);
This JavaScript code snippet imports the necessary modules from Redux and Redux Persist, defines a persist configuration object for Redux Persist with a key and the storage backend, wraps the root reducer with persistReducer using this configuration, and creates the Redux store and the persistor that will be used to rehydrate the state from the storage.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>,
document.getElementById('root')
);
This JavaScript code snippet for a React application integrates the store and persistor with the React front-end. It renders the root component inside a Provider component to make the Redux store available to all connect() calls in the component tree. Additionally, it wraps the App component inside the PersistGate which delays the rendering of the UI until the persisted state has been retrieved and saved to redux.
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}
#root {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
This CSS snippet provides basic global styles for the body, and styles for the root element where the React application is mounted. These styles are ensuring that the application takes the full height of the viewport and is centered.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redux Persist Demo</title>
</head>
<body>
<div id="root"></div>
<!-- Scripts will be added here -->
</body>
</html>
This is the HTML template where the React application using Redux Persist will be mounted. The div with the id of 'root' is the mounting point for the React app, and scripts for the React build will be placed before the closing body tag.