ngrx-store-localstorage vs redux-persist
State Management Persistence Libraries
ngrx-store-localstorageredux-persistSimilar Packages:

State Management Persistence Libraries

State management persistence libraries are tools designed to help developers maintain the state of their applications across sessions by storing it in a persistent storage solution, such as local storage or session storage. These libraries enable applications to retrieve and restore their state even after a page refresh or browser restart, enhancing user experience and application reliability. They are particularly useful in single-page applications (SPAs) where state management is critical for maintaining a seamless user experience.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
ngrx-store-localstorage062042.3 kB522 months agoMIT
redux-persist013,001-5967 years agoMIT

Feature Comparison: ngrx-store-localstorage vs redux-persist

Integration

  • ngrx-store-localstorage:

    ngrx-store-localstorage is specifically designed for Angular applications using NgRx. It integrates directly with the NgRx store, allowing for easy configuration and automatic synchronization of state with local storage, making it a natural choice for Angular developers.

  • redux-persist:

    redux-persist is built for Redux and can be used with any JavaScript framework or library. It provides a flexible API that allows developers to easily configure how and what to persist, making it versatile for various application architectures.

Configuration Flexibility

  • ngrx-store-localstorage:

    ngrx-store-localstorage offers limited configuration options focused on the NgRx store structure. It is straightforward to set up but may not provide the same level of customization as other libraries, making it less suitable for complex persistence needs.

  • redux-persist:

    redux-persist provides extensive configuration options, allowing developers to customize the storage mechanism, versioning, and data transformations. This flexibility makes it suitable for a wide range of applications with varying persistence requirements.

Data Serialization

  • ngrx-store-localstorage:

    ngrx-store-localstorage automatically serializes and deserializes the state when saving to and loading from local storage, ensuring that the state is stored in a format that can be easily retrieved and used by the application.

  • redux-persist:

    redux-persist also handles serialization and deserialization of state, but it allows for custom transforms to be applied, giving developers control over how their state is stored and retrieved, which can be beneficial for optimizing performance or handling specific data formats.

Performance

  • ngrx-store-localstorage:

    ngrx-store-localstorage is designed to be lightweight and efficient, focusing on minimizing the performance impact of state persistence. However, it may not offer advanced performance optimizations for large state trees or complex applications.

  • redux-persist:

    redux-persist can introduce some performance overhead due to its flexibility and features. Developers can mitigate this by using features like selective persistence, which allows them to specify which parts of the state should be persisted, thus optimizing performance.

Community and Support

  • ngrx-store-localstorage:

    ngrx-store-localstorage has a smaller community compared to redux-persist, which may result in less available documentation and fewer third-party resources. However, it benefits from the strong Angular and NgRx community support.

  • redux-persist:

    redux-persist has a large and active community, providing extensive documentation, tutorials, and third-party plugins. This makes it easier for developers to find solutions to common problems and integrate with other libraries.

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

  • ngrx-store-localstorage:

    Choose ngrx-store-localstorage if you are using Angular with NgRx for state management and want a solution that integrates seamlessly with the NgRx store, providing a straightforward way to persist state across sessions while leveraging Angular's reactive programming model.

  • redux-persist:

    Choose redux-persist if you are using Redux for state management in a React or other JavaScript applications. It offers a flexible and customizable way to persist your Redux store, allowing for various storage backends and configuration options to suit different application needs.

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.