DEV Community

Ricards Taujenis
Ricards Taujenis

Posted on • Updated on

How to Persist state with Redux Persist in React

Image description

The more complicated the project is the more necesity it is to handle state in your React applications across different components. But there are times when you want persistent state for example on page refresh to not clear data in your store, thus persistant state comes in play.
Configuration
As a no brainer you should have already redux installed in your project app next comes this. 👇

npm i redux-persist

For more info can read up in the docs here.
Incorporating Redux Persist Ones installed
Ones installed and no npm errros occur(hopefully you never know with npm!).
In your store.ts or other file where you have defined your app state what you want to keep persistent you add.

import { createStore, Reducer } from 'redux';
import { AuthenticationUserStates } from '../types/global';
import { persistStore, persistReducer } from 'redux-persist' //Adding persistStore, Reducer
import storage from 'redux-persist/lib/storage' //storage 

const authReducer: Reducer<AuthenticationUserStates, any> = ( //Own state code bloc
    state = initialState,
    action: any
) => {
    ...
    }
};

const persistConfig = { // create persistConfig with whitelisting state
    key: 'root',
    storage,
    whitelist: ['authenticated',  'userID', 'email'],
}

const persistedReducer = persistReducer(persistConfig, authReducer) // persist data

const store = createStore(persistedReducer); // invoke persistentReducer to createStore
const persistor = persistStore(store);

export { store, persistor }; // export both
Enter fullscreen mode Exit fullscreen mode

Here as can see I whitelisted states I want to persist even when page is refreshed other thing to note that bellows import

import storage from 'redux-persist/lib/storage'

actually works as localstorage. What you could define without redux-persist but it can be more convinient to use a package.
Both store and persistor needs to be exported.
Wrapping it to your App.tsx
As a follow up you have to wrap it arround your App.tsx(or App.jsx)

// Other imports
import { Provider, useSelector } from 'react-redux';
import { PersistGate } from "redux-persist/integration/react";
import { store, persistor } from './store/store';

const App: React.FC = () => {
     const isAuthenticated = useSelector((state: AuthenticationUserStates) => state.authenticated);

     return (
         <Provider store={store}>
             <PersistGate loading={null} persistor={ persistor }>
                 <>
                // Other code block
                 </>
             </PersistGate>
         </Provider>
              );
    }
Enter fullscreen mode Exit fullscreen mode

So to shortly cover these steps.

Provider: Is a React Redux library which makes the Redux store available to the rest of your application.

PersistGate: This is a component from Redux Persist library which delays the rendering of your app's UI until the persisted state has been retrieved and saved to redux.

: This wraps the entire application and makes the Redux store available to all components.

: Wraps the component and ensures that your application doesn't render until the persisted state has been retrieved and saved to redux.

That should sum it up as a nutshell. In my case on page refresh wanted to keep userID, email and authenticated(bool) as persistent authToken I am retriving from Redis with Go. If you want to see that part can watch the YouTube video bellow where you can find as well GitHub repo to project. 👇

https://youtu.be/SQrsDZU_D5k


When you have triggered your state you should be able to see it in localstorage as well.


Hope the use of redux-persist is clarified in this article and you will be able to utilize the streanght of it but remember not everything should be persistent thus authToken I stored in Redis for more of a secure option.

Top comments (3)

Collapse
 
hasibrashid profile image
Hasib Al Rashid

Nice Post! But would appreciate it if you'd use the code tag while writing the markdown in this post. That would be beneficial for other readers of this post.

Great job by the way! 💖

Collapse
 
mozes721 profile image
Ricards Taujenis

Ok thanks will take it in account the next time!

Collapse
 
mozes721 profile image
Ricards Taujenis

I do use code tags but markup here seems to be broken have to fix it