npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

eclifford-redux-persist

v3.2.1

Published

persist and rehydrate redux stores

Downloads

5

Readme

Redux Persist

Persist and rehydrate a redux store.

Redux Persist is performant, easy to implement, and easy to extend.

V3 changelog These docs are for redux-persist v3. This version removes the automatic action buffer, if you relied on this functionality you can now implement it explicitly.

Migrations are hot off the presses, feedback welcome!

npm i --save redux-persist

build status npm version npm downloads

Basic Usage

Basic usage requires adding three lines to a traditional redux application:

import {persistStore, autoRehydrate} from 'redux-persist'
const store = createStore(reducer, undefined, autoRehydrate())
persistStore(store)

For per reducer rehydration logic, you can opt-in by adding a handler to your reducer:

import {REHYDRATE} from 'redux-persist/constants'
//...
case REHYDRATE:
  var incoming = action.payload.myReducer
  if (incoming) return {...state, ...incoming, specialKey: processSpecial(incoming.specialKey)}
  return state

You may also need to configure the persistence layer, or take action after rehydration has completed:

persistStore(store, {blacklist: ['someTransientReducer']}, () => {
  console.log('rehydration complete')
})

And if things get out of wack, just purge the storage

persistStore(store, config, callback).purge(['someReducer']) //or .purgeAll()

API

persistStore(store, [config, callback])

  • arguments
    • store redux store The store to be persisted.
    • config object
      • blacklist array keys (read: reducers) to ignore
      • whitelist array keys (read: reducers) to persist, if set all other keys will be ignored.
      • storage object a conforming storage engine.
      • transforms array transforms to be applied during storage and during rehydration.
      • debounce integer debounce interval applied to storage calls.
    • callback function will be called after rehydration is finished.
  • returns persistor object

persistor object

  • the persistor object is returned by persistStore with the following methods:
    • .purge(keys)
      • keys array An array of keys to be purged from storage. If not provided all keys will be purged.
    • .rehydrate(incoming, options)
      • incoming object Data to be rehydrated into the store.
      • options object If serial:true, incoming should be a string, that will be deserialized and passed through the transforms defined in the persistor.
      • Manually rehydrates the store with the passed data, dispatching the rehydrate action.

autoRehydrate()

  • This is a store enhancer that will automatically shallow merge the persisted state for each key. Additionally it queues any actions that are dispatched before rehydration is complete, and fires them after rehydration is finished.

constants

  • import constants from 'redux-persist/constants'. This includes rehydration action types, and other relevant constants.

Alternate Usage

getStoredState / createPersistor

import {getStoredState, autoRehydrate, createPersistor} from 'redux-persist'

// ...

const persistConfig = { /* ... */ }

getStoredState(persistConfig, (err, restoredState) => {
  const store = createStore(reducer, restoredState)
  const persistor = createPersistor(store, persistConfig)
})

Notes:

  • under the hood, persistStore simply implements both getStoredState and createPersistor
  • getStoredState supports promises as well

Secondary Persistor

import {persistStore, createPersistor} from 'redux-persist'
const persistor = persistStore(store) // persistStore restores and persists
const secondaryPersistor = createPersistor(store, {storage: specialBackupStorage}) // createPersistor only persists

Storage Backends

  • localStorage (default) web
  • localForage (recommended) web, see usage below
  • AsyncStorage for react-native
  • custom any conforming storage api implementing the following methods: setItem getItem removeItem getAllKeys. [example]
// react-native
import {AsyncStorage} from 'react-native'
persistStore(store, {storage: AsyncStorage})

// web with recommended localForage
import localForage from 'localForage'
persistStore(store, {storage: localForage})

Transforms

Transforms allow for arbitrary state transforms before saving and during rehydration.

  • immutable - support immutable reducers
  • compress - compress your serialized state with lz-string
  • encrypt - encrypt your serialized state with AES
  • custom transforms:
import { createTransform, persistStore } from 'redux-persist'

let myTransform = createTransform(
  (inboundState) => specialSerialize(inboundState),
  (outboundState) => specialDeserialize(outboundState),
  {whitelist: ['specialReducer']}
)

persistStore(store, {transforms: [myTransform]})

Action Buffer

A common mistake is to fire actions that modify state before rehydration is complete which then will be overwritten by the rehydrate action. You can either defer firing of those actions until rehydration is complete, or you can use an action buffer.

Earlier versions of redux persist included the action buffer by default, but it was removed in v3.

Why Redux Persist

  • Performant out of the box (uses a time iterator and operates on state partials)
  • Keeps custom rehydration logic in the reducers (where it intuitively belongs)
  • Supports localStorage, react-native AsyncStorage, or any conforming storage api

Because persisting state is inherently stateful, persistStore lives outside of the redux store. Importantly this keeps the store 'pure' and makes testing and extending the persistor much easier.

About Auto Rehydrate

autoRehydrate is a store enhancer that automatically rehydrates state.

While auto rehydration works out of the box, individual reducers can opt in to handling their own rehydration, allowing for more complex operations like data transforms and cache invalidation. Simply define a handler for the rehydrate action in your reducer, and if the state is mutated, auto rehydrate will skip that key.

Auto rehydrate is provided as a convenience. In a large application, or one with atypical reducer composition, auto rehydration may not be convenient. In this case, simply omit autoRehydrate. Rehydration actions will still be fired by persistStore, and can then be handled individually by reducers or using a custom rehydration handler.