redux-persist README

The project's README from github.com/endograph/redux-persist. As one markdown file: README.md.

redux-persist

Quickstart · API · Storage engines · npm

redux-persist

CI npm npm next downloads license

Persist and rehydrate a redux store. Your state is saved to storage as it changes and restored into the store when your app starts.

Hey all! redux-persist is maintained again, and v7 is in beta (npm install redux-persist@next): Redux Toolkit 2 support with no extra setup, a fix for stored data getting wiped (#809), and lots more. Please try it and tell us how it goes in the v7 beta discussion.

These docs are for v7, which needs Redux 5 or Redux Toolkit 2. Upgrading from 6? Read the migration guide; your stored data carries over as is. For 6.x, see the v6 docs.

Quickstart

npm install redux-persist

Wrap your root reducer and create a persistor alongside the store:

// app/store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/storage' // localStorage on the web
import userReducer from './features/user/userSlice'
import configReducer from './features/config/configSlice'

const rootReducer = combineReducers({
  user: userReducer,
  config: configReducer
})

const persistConfig = {
  key: 'root',
  version: 1,
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = configureStore({
  reducer: persistedReducer,
})

export const persistor = persistStore(store)

If you use React, wrap your root component in PersistGate. It holds off rendering until the stored state has been loaded back into redux. loading can be null or any React element, e.g. loading={<Loading />}.

import { PersistGate } from 'redux-persist/react'
import { store, persistor } from './app/store'

// ... normal setup, import components etc.

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <RootComponent />
      </PersistGate>
    </Provider>
  );
};

If you'd rather not gate rendering, useRehydrated(persistor) from redux-persist/react returns whether stored state has loaded.

Every app has to decide how many levels of stored state to merge into its initial state. The default is one level; read state reconcilers before you ship.

React Native

Pass your storage engine explicitly:

import AsyncStorage from '@react-native-async-storage/async-storage'

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
}

Server rendering

redux-persist/storage works during server rendering (Next.js and others): on the server it stores nothing, and stored state is loaded in the browser. With the Next.js App Router, render PersistGate from a Client Component; see PersistGate.

Choosing what's saved

denylist and allowlist pick top-level keys:

persistReducer({ key: 'root', storage, denylist: ['navigation'] }, rootReducer) // navigation will not be persisted

persistReducer({ key: 'root', storage, allowlist: ['navigation'] }, rootReducer) // only navigation will be persisted

They're checked against your state's keys, so a typo is a type error. If you declare the config separately, annotate it with PersistConfig<RootState> or use as const on the array. The older names blacklist and whitelist still work.

For keys you can't list ahead of time, pass a function that's called with each top-level key:

persistReducer({ key: 'root', storage, denylist: key => key.startsWith('temp') }, rootReducer) // keys starting with temp will not be persisted

To go deeper than one level, use nested persists.

Resetting state on logout

Reset state inside the reducer you pass to persistReducer, so the reset state is saved too:

const rootReducer = (state, action) =>
  appReducer(action.type === 'user/logout' ? undefined : state, action)

const persistedReducer = persistReducer(persistConfig, rootReducer)

The reset state is saved like any other change. To write it right away (for example before the app might close), await persistor.flush() after dispatching the action.

Don't reset above persistReducer (by wrapping the persisted reducer, or with a store enhancer that replaces the whole state): that removes the _persist key, so the state stops being saved, and the previous user's state is loaded again on the next launch. redux-persist logs an error in development when this happens.

Learn more

Contributing

Bug reports and pull requests are welcome; see CONTRIBUTING.md, especially before changing anything that touches stored data. Questions and feature ideas go in Discussions. Feedback on the v7 beta goes in the v7 beta discussion.

redux-persist (endograph/redux-persist)

Searching Database…

What is this?Redux Persist is a library that saves (persists) your Redux store to storage and automatically rehydrates it when your app reloads, so state survives page refreshes or app restarts.
Is it a library I add to my existing Redux setup, or a standalone tool?It is a library you install into an existing Redux app; you wrap your reducer with persistReducer and call persistStore on your store.
How do I add it to my project?Install with npm install redux-persist, wrap your root reducer with persistReducer(config, reducer), create a persistor with persistStore(store), and optionally wrap your React app in PersistGate to delay rendering until rehydration completes.
Do I need a specific storage engine, or does it work out of the box?It ships with localStorage and sessionStorage engines for web, and supports a long list of community storage engines (electron-store, react-native-fs, Expo filesystem/SecureStore, IndexedDB via localForage, PouchDB, Realm, and more) that you pass into the config.
What's the main gotcha when setting this up?You must pick the right state reconciler (how incoming persisted state merges with your reducer's initial state) since the default only shallow-merges one level deep, which can silently drop nested state if you're not careful.
Does this only work for React apps?No, the core library is framework-agnostic and works with any Redux store (web or React Native); PersistGate is just an optional React-specific convenience component.
Can I only persist part of my state?Yes, use the whitelist/blacklist config options to include or exclude specific reducer keys, or nest persistReducer deeper for finer-grained control.
How do I migrate stored state when my data shape changes?persistReducer accepts a migrate function that runs on the loaded state before reconciliation; redux-persist ships createMigrate to build synchronous migrations between versioned state shapes.
Can I transform data before saving it, like compressing or encrypting it?Yes, Transforms let you modify state right before it is persisted and right after it is rehydrated, and community packages exist for compression (lz-string), AES encryption, and filtering subsets of state.
What happened to the project's maintenance status?The project was handed to a new maintainer in September 2021 who is triaging issues, upgrading dependencies, and moving the codebase from Flow to TypeScript and from Ava to Jest.
Creator
endograph
Size
1.4 MB
Stars
13K
Age
11y
Commits · 90 Days