ngrx-store-localstorage vs redux-persist
Persisting State in Redux and NgRx Applications
ngrx-store-localstorageredux-persistSimilar Packages:

Persisting State in Redux and NgRx Applications

ngrx-store-localstorage and redux-persist are libraries designed to save application state to the browser's local storage (or other storage engines) so data survives page reloads. ngrx-store-localstorage is a specialized meta-reducer built specifically for the NgRx ecosystem in Angular applications. It hooks directly into the NgRx store lifecycle to serialize and rehydrate state with minimal configuration. redux-persist is a framework-agnostic persistence layer primarily used with Redux in React, Vue, or vanilla JavaScript projects. It offers a more complex architecture involving a persistStore function, a PersistGate component to block rendering until rehydration is complete, and support for various storage engines beyond just local storage.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
ngrx-store-localstorage062442.3 kB528 months agoMIT
redux-persist012,959-5937 years agoMIT

Persisting State: ngrx-store-localstorage vs redux-persist

Saving user data, preferences, or session tokens so they survive a page refresh is a common requirement in modern web apps. Both ngrx-store-localstorage and redux-persist solve this problem by syncing your store to the browser's local storage. However, they are built for different ecosystems and follow distinct architectural patterns. Let's look at how they handle integration, rehydration, and advanced scenarios.

πŸ—οΈ Integration Style: Meta-Reducers vs Store Enhancers

The most fundamental difference lies in how these libraries plug into your state management system.

ngrx-store-localstorage acts as a meta-reducer. In NgRx, meta-reducers wrap the root reducer to intercept actions before they reach your feature reducers. This approach is purely functional and fits naturally into the Angular/NgRx architecture. You simply pass the meta-reducer to the StoreModule.forRoot configuration.

// ngrx-store-localstorage: Integrated as a meta-reducer
import { StoreModule } from '@ngrx/store';
import { localStorageSync } from 'ngrx-store-localstorage';

export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return localStorageSync({ keys: ['user', 'settings'] })(reducer);
}

@NgModule({
  imports: [
    StoreModule.forRoot(reducers, {
      metaReducers: [localStorageSyncReducer]
    })
  ]
})
export class AppModule {}

redux-persist uses a store enhancer and a separate persistStore function. It does not just wrap the reducer; it creates a persistence object that manages the engine. In React applications, this usually requires wrapping your app in a PersistGate component to delay rendering until the state is restored from storage.

// redux-persist: Requires persistStore and PersistGate
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import { PersistGate } from 'redux-persist/integration/react';

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

const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(persistedReducer);
const persistor = persistStore(store);

// In your React App component
<Provider store={store}>
  <PersistGate loading={null} persistor={persistor}>
    <App />
  </PersistGate>
</Provider>

⏳ Rehydration: Automatic vs Gated Rendering

How the application behaves while waiting for data to load from disk differs significantly between the two.

ngrx-store-localstorage performs rehydration synchronously during the store initialization phase (inside the meta-reducer). By the time your Angular components initialize, the state is already populated from local storage. There is no need for a loading gate or special component to wait for data.

// ngrx-store-localstorage: No gate needed
// State is available immediately in components
@Component({
  selector: 'app-user',
  template: `<div *ngIf="user$ | async as user">{{ user.name }}</div>`
})
export class UserComponent {
  user$ = this.store.select('user'); // Data is ready here
}

redux-persist often handles rehydration asynchronously. Because reading from storage (especially IndexedDB or large JSON blobs) can take time, the library provides a PersistGate. This component pauses the rendering of its children until the persisted state has been retrieved and merged into the store. This prevents UI errors caused by rendering with empty initial state.

// redux-persist: Explicitly handles loading state
const LoadingScreen = () => <div>Loading saved data...</div>;

// Children inside PersistGate will not render until rehydration completes
<PersistGate loading={<LoadingScreen />} persistor={persistor}>
  <Dashboard /> 
</PersistGate>

πŸ› οΈ Configuration and Filtering

Both libraries allow you to choose which parts of the state to save, but the configuration syntax reflects their host frameworks.

ngrx-store-localstorage uses a simple function call where you specify an array of keys. It also supports custom serialization logic if you need to handle complex objects like Dates or Maps.

// ngrx-store-localstorage: Key array and custom serialize
localStorageSync({
  keys: ['auth', 'preferences'],
  rehydrate: true,
  serialize: (state) => {
    // Custom logic to handle Date objects
    return JSON.stringify(state, (key, value) => 
      value instanceof Date ? { __type: 'Date', value: value.getTime() } : value
    );
  }
});

redux-persist uses a configuration object passed to persistReducer. It supports whitelist (only save these) or blacklist (save everything except these). It also has built-in support for transforms to handle data conversion.

// redux-persist: Whitelist/Blacklist and Transforms
const persistConfig = {
  key: 'root',
  storage,
  whitelist: ['auth', 'settings'], // Only persist these keys
  transforms: [
    // Built-in or custom transforms for complex data
  ]
};

πŸ”„ State Migrations: Handling Schema Changes

When you change the shape of your state (e.g., renaming a field), old data in local storage might break your app. Handling these migrations is a key differentiator.

ngrx-store-localstorage does not have a built-in migration system. If you change your state structure, you typically need to manually check for version numbers in your reducer or clear the storage if the data shape is incompatible. You might write a custom meta-reducer to handle this logic yourself.

// ngrx-store-localstorage: Manual migration logic required
export function migrationMetaReducer(reducer: ActionReducer<any>): ActionReducer<any> {
  return (state, action) => {
    if (action.type === '@ngrx/store/init') {
       const storedState = localStorage.getItem('ngrx-store');
       if (storedState) {
         const parsed = JSON.parse(storedState);
         // Manually check and fix old structure
         if (!parsed.user.fullName && parsed.user.name) {
            parsed.user.fullName = parsed.user.name;
         }
       }
    }
    return reducer(state, action);
  };
}

redux-persist includes a robust, built-in migration system. You define a migrate function in your config that receives the old state and a version number. This makes updating state schemas across app versions much safer and cleaner.

// redux-persist: Built-in migration support
const migrations = {
  2: (state) => {
    // Migrate from version 1 to 2
    return {
      ...state,
      user: {
        ...state.user,
        fullName: state.user.name // Rename field
      }
    };
  }
};

const persistConfig = {
  key: 'root',
  version: 2,
  storage,
  migrate: createMigrate(migrations, { debug: false })
};

🌐 Ecosystem and Storage Engines

The choice of storage engine is often dictated by the platform you are building for.

ngrx-store-localstorage is tightly coupled to the browser's localStorage API. While you can technically inject a different storage service in Angular, the package is optimized and tested primarily for synchronous browser storage. It is not designed for React Native or server-side rendering (SSR) environments out of the box.

// ngrx-store-localstorage: Defaults to window.localStorage
// Best for standard Angular web apps
localStorageSync({ keys: ['cart'] }); 

redux-persist is designed to be storage-agnostic. It works with localStorage, sessionStorage, IndexedDB, and even AsyncStorage for React Native mobile apps. This flexibility makes it the go-to choice for cross-platform applications.

// redux-persist: Swappable storage engines
import AsyncStorage from '@react-native-async-storage/async-storage';

// Works seamlessly in React Native
const persistConfig = {
  key: 'root',
  storage: AsyncStorage 
};

🀝 Similarities: Shared Core Concepts

Despite their architectural differences, both libraries share the same fundamental goal and basic capabilities.

1. πŸ’Ύ Automatic Syncing

Both libraries automatically save state changes to storage whenever an action updates the store. You don't need to manually call setItem.

// Both: Dispatching an action triggers an auto-save
store.dispatch({ type: 'UPDATE_USER', payload: newUser });
// Data is written to localStorage automatically by both libraries

2. πŸ”‘ Key-Based Selection

Both allow you to limit what gets saved. You rarely want to persist the entire store (e.g., avoiding large API caches or UI states).

// ngrx-store-localstorage
localStorageSync({ keys: ['auth'] });

// redux-persist
whitelist: ['auth']

3. 🧩 Serialization

Both handle converting your JavaScript state objects into JSON strings for storage and parsing them back upon load. They both allow custom serialization logic for non-JSON data types.

// Both support custom serializers for special types like Dates
// ngrx: serialize option
// redux-persist: transforms array

πŸ“Š Summary: Key Differences

Featurengrx-store-localstorageredux-persist
Primary EcosystemAngular (NgRx)React, Vue, Vanilla (Redux)
Integration MethodMeta-ReducerStore Enhancer + PersistGate
RehydrationSynchronous (Immediate)Asynchronous (Often requires Gate)
MigrationsManual implementation requiredBuilt-in versioned migration system
Storage EnginesPrimarily LocalStorageLocalStorage, Async, IndexedDB, etc.
BoilerplateLow (Functional)Medium (Config + Components)

πŸ’‘ The Big Picture

ngrx-store-localstorage is the pragmatic choice for Angular developers. It feels like a natural extension of NgRx, leveraging meta-reducers to keep logic functional and centralized. If you are in the Angular ecosystem, this package saves you from fighting against the framework's architecture. It is simple, effective, and "just works" for standard web apps.

redux-persist is the powerhouse for the React and cross-platform world. Its ability to handle asynchronous storage, provide a loading gate, and manage complex state migrations makes it indispensable for large-scale applications or mobile apps (React Native). While it introduces more boilerplate, that complexity buys you significant control and safety when managing state over the long term.

Final Thought: Do not try to force redux-persist into an Angular app if ngrx-store-localstorage meets your needsβ€”the integration will feel unnatural. Conversely, if you are building a React Native app, redux-persist is essentially the only viable option due to its storage engine flexibility. Choose the tool that respects your framework's conventions.

How to Choose: ngrx-store-localstorage vs redux-persist

  • ngrx-store-localstorage:

    Choose ngrx-store-localstorage if you are building an Angular application using NgRx for state management. It is the ideal choice because it integrates natively as a meta-reducer, requiring no extra components or complex setup gates. It respects Angular's dependency injection system and works seamlessly with NgRx DevTools without additional configuration. Avoid this package if you are not using Angular or NgRx, as it relies heavily on Angular-specific types and internals.

  • redux-persist:

    Choose redux-persist if you are working with Redux in a React, Vue, or vanilla JavaScript environment, or if you need advanced persistence features like migrating old state schemas or using custom storage engines (e.g., IndexedDB, AsyncStorage for React Native). It is the standard solution for the React ecosystem, offering a PersistGate to prevent UI flicker during rehydration. Do not use this package in a standard Angular/NgRx project unless you have a specific need for its migration tools that ngrx-store-localstorage cannot meet, as it introduces unnecessary complexity and non-Angular patterns.

README for ngrx-store-localstorage

ngrx-store-localstorage

bundle size npm weekly downloads semantic-release CircleCI

Simple syncing between ngrx store and local or session storage.

Dependencies

ngrx-store-localstorage depends on @ngrx/store and Angular 20+.

Usage

npm install ngrx-store-localstorage --save
  1. Wrap localStorageSync in an exported function.
  2. Include in your meta-reducers array in StoreModule.forRoot.
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import {
  StoreModule,
  ActionReducerMap,
  ActionReducer,
  MetaReducer,
} from "@ngrx/store";
import { localStorageSync } from "ngrx-store-localstorage";
import { reducers } from "./reducers";

const reducers: ActionReducerMap<IState> = { todos, visibilityFilter };

export function localStorageSyncReducer(
  reducer: ActionReducer<any>,
): ActionReducer<any> {
  return localStorageSync({ keys: ["todos"] })(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];

@NgModule({
  imports: [BrowserModule, StoreModule.forRoot(reducers, { metaReducers })],
})
export class MyAppModule {}

API

localStorageSync(config: LocalStorageConfig): Reducer

Provide state (reducer) keys to sync with local storage. Returns a meta-reducer.

Arguments

  • config An object that matches with the LocalStorageConfig interface, keys is the only required property.

LocalStorageConfig

An interface defining the configuration attributes to bootstrap localStorageSync. The following are properties which compose LocalStorageConfig:

  • keys (required) State keys to sync with local storage. The keys can be defined in two different formats:

    • string[]: Array of strings representing the state (reducer) keys. Full state will be synced (e.g. localStorageSync({keys: ['todos']})).

    • object[]: Array of objects where for each object the key represents the state key and the value represents custom serialize/deserialize options. This can be one of the following:

      • An array of properties which should be synced. This allows for the partial state sync (e.g. localStorageSync({keys: [{todos: ['name', 'status'] }, ... ]})).

      • A reviver function as specified in the JSON.parse documentation.

      • An object with properties that specify one or more of the following:

        • serialize: A function that takes a state object and returns a plain json object to pass to json.stringify.

        • deserialize: A function that takes that takes the raw JSON from JSON.parse and builds a state object.

        • replacer: A replacer function as specified in the JSON.stringify documentation.

        • space: The space value to pass JSON.stringify.

        • reviver: A reviver function as specified in the JSON.parse documentation.

        • filter: An array of properties which should be synced (same format as the stand-alone array specified above).

        • encrypt: A function that takes a state string and returns an encrypted version of that string. e.g. (state: string) => btoa(state)

        • decrypt: A function that takes a state string and returns a decrypted version of that string. e.g. (state: string) => atob(state)

  • rehydrate (optional) boolean: Pull initial state from local storage on startup, this will default to false.

  • storage (optional) Storage: Specify an object that conforms to the Web Storage API interface to use, this will default to localStorage.

  • removeOnUndefined (optional) boolean: Specify if the state is removed from the storage when the new value is undefined, this will default to false.

  • storageKeySerializer (optional) (key: string) => string: Custom serialize function for storage keys, used to avoid Storage conflicts.

  • restoreDates (boolean? = true): Restore serialized date objects. If you work directly with ISO date strings, set this option to false.

  • syncCondition (optional) (state) => boolean: When set, sync to storage medium will only occur when this function returns a true boolean. Example: (state) => state.config.syncToStorage will check the state tree under config.syncToStorage and if true, it will sync to the storage. If undefined or false it will not sync to storage. Often useful for "remember me" options in login.

  • checkStorageAvailability (boolean? = false): Specify if the storage availability checking is expected, i.e. for server side rendering / Universal.

  • mergeReducer (optional) (state: any, rehydratedState: any, action: any) => any: Defines the reducer to use to merge the rehydrated state from storage with the state from the ngrx store. If unspecified, defaults to performing a full deepmerge on an INIT_ACTION or an UPDATE_ACTION.

Usage

Key Prefix

localStorageSync({
  keys: ["todos", "visibilityFilter"],
  storageKeySerializer: (key) => `cool_${key}`,
});

In above example Storage will use keys cool_todos and cool_visibilityFilter keys to store todos and visibilityFilter slices of state). The key itself is used by default - (key) => key.

Target Depth Configuration

localStorageSync({
  keys: [
    { feature1: [{ slice11: ["slice11_1"], slice14: ["slice14_2"] }] },
    { feature2: ["slice21"] },
  ],
});

In this example, feature1.slice11.slice11_1, feature1.slice14.slice14_2, and feature2.slice21 will be synced to localStorage.feature1 and localStorage.feature2.

Known Workarounds

  1. Sync state across multiple tabs

Release Notes / Changelog

From version 10 onwards, check GitHub Releases for release notes. For older versions check the CHANGELOG.md.

Contributing

See CONTRIBUTING.md for instructions on how to contribute.