Get started with redux-persist CDN

MIT licensed

Redux-persist: Middleware saving/restoring Redux state to localStorage or alternatives.

Tags:
  • redux
  • redux-middleware
  • localstorage
  • redux-persist
  • redux-storage
  • redux-rehydrate

Stable version

Copied!

How to start using redux-persist CDN


// Import required libraries
import { createStore, applyMiddleware } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // Defaults to localStorage if omitted
import ReduxThunk from 'redux-thunk';

// Define the reducer
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    default:
      return state;
  }
};

// Configure persistReducer
const persistConfig = {
  key: 'root',
  storage,
};
const persistedReducer = persistReducer(persistConfig, reducer);

// Create the Redux store with middleware
const store = createStore(persistedReducer, applyMiddleware(ReduxThunk));

// Create the persistor and run it
const persistor = persistStore(store);

// Start listening for state changes and save them
persistor.subscribe((state) => {
  console.log('State has been updated:', state);
});

// Export the store and persistor for usage
export { store, persistor };
Copied!
Copied!
Copied!
Copied!

All versions