React Store Adapter

Storagefy's React adapter provides seamless persistence for your React state management solutions. Compatible with popular libraries like Redux, Zustand, Jotai, and custom stores, this adapter synchronizes your application state with your chosen storage backend across page reloads and browser sessions.

1. Basic Usage

The React adapter works with various React state management solutions, making it easy to persist your application state:

        
import { startStoragefy, getReactAdapter } from "storagefy";

// Initialize the storage backend
startStoragefy({
  dbName: "my-react-app",
  adapter: "indexedDB", // or "localStorage" or "sessionStorage"
  encrypt: true,
  channelName: "react-sync",  // the channel the tabs talk on…
  enableSyncTabs: true   // …and this storage tells them about its writes
});

// Get the React adapter
const { setInStorage, getFromStorage } = getReactAdapter();

// Connect with your store (works with Redux, Zustand, and more)
await getFromStorage(store, "app-state"); // Always call this before setInStorage
await setInStorage(store, "app-state", {
  timeout: 86400000, // 24 hour expiration
  ignoreKeys: ["temporaryData", "user.password"],
  syncTabs: true
});
        
      

2. Using the Helper Function

For a more concise approach, use the setReactStorage helper function:

        
import { startStoragefy, setReactStorage } from "storagefy";

// Initialize storage backend
startStoragefy({
  dbName: "my-react-app",
  adapter: "localStorage"
});

// Use the helper function to simplify the process
await setReactStorage(store, "app-state", {
  timeout: 3600000, // 1 hour
  ignoreKeys: ["_temp", "user.password"],
  syncTabs: true
});
        
      

3. Test It

3.1 Redux

3.2 Zustand

3.3 Jotai

4. Advanced Configuration

You can directly instantiate the ReactAdapter class for more advanced control:

        
import { ReactAdapter, IndexedDBAdapter } from "storagefy";

// Create storage adapter instance
const storageAdapter = new IndexedDBAdapter({ 
  dbName: "react-app",
  encrypt: true
});

// Create React adapter with the storage adapter
const reactAdapter = new ReactAdapter(storageAdapter);

// Connect with your store
await reactAdapter.getFromStorage(store, "user-settings");
await reactAdapter.setInStorage(store, "user-settings", {
  ignoreKeys: ["authToken", "user.password"],
  timeout: 604800000 // 1 week
});
        
      

5. Supported State Management Libraries

The React adapter is designed to work with multiple state management solutions:

Redux

Works with standard Redux stores by utilizing getState, dispatch, and subscribe methods.

          
import { createStore } from 'redux';
import { startStoragefy, setReactStorage } from "storagefy";

const reducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'SET_STATE_FROM_STORAGE': // getFromStorage: the state kept
    case 'STORAGEFY_UPDATE':       // syncTabs: the state of another tab
      return { ...state, ...action.payload };
    default:
      return state;
  }
};

const store = createStore(reducer);

// Persist Redux store
await setReactStorage(store, "redux-state");
          
        

Note: your Redux reducer handles SET_STATE_FROM_STORAGE (the state loaded bygetFromStorage) and, with syncTabs, STORAGEFY_UPDATE (the state of another tab). setInStorage resolves once the state is written for the first time (or found stored already).

Zustand

Compatible with Zustand stores using getState, setState, and subscribe methods.

          
import create from 'zustand';
import { startStoragefy, setReactStorage } from "storagefy";

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  reset: () => set({ count: 0 })
}));

// Persist Zustand store
await setReactStorage(useStore, "zustand-state");
          
        

Jotai

Works with Jotai atom values using get, set, and subscription mechanisms.

          
import { atom, useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { startStoragefy, getReactAdapter } from "storagefy";

const countAtom = atom(0);

// For Jotai, you'll need a store-like wrapper
const jotaiStore = {
  get: () => countAtom.init,
  set: (value) => {
    countAtom.init = value;
    // Trigger updates to subscribers
  },
  subscribe: (callback) => {
    // Setup subscription to atom changes
    // Return unsubscribe function
  }
};

// Get the adapter
const { setInStorage, getFromStorage } = getReactAdapter();

// Persist Jotai state
await getFromStorage(jotaiStore, "jotai-state");
await setInStorage(jotaiStore, "jotai-state");
          
        

Custom React State Hooks

You can adapt custom React hooks or state management solutions by creating a compatible store interface.

          
import { useState, useEffect } from 'react';
import { startStoragefy, setReactStorage } from "storagefy";

// Create a store-like interface for your custom hook
function createStore(initialState) {
  let state = initialState;
  const listeners = new Set();
  
  return {
    getState: () => state,
    setState: (newState) => {
      state = typeof newState === 'function' ? newState(state) : newState;
      listeners.forEach(listener => listener(state));
    },
    subscribe: (listener) => {
      listeners.add(listener);
      return () => listeners.delete(listener);
    }
  };
}

const customStore = createStore({ theme: 'light', language: 'en' });

// Persist custom store
await setReactStorage(customStore, "custom-state");
          
        

6. Configuration Options

The setInStorage method accepts the following options:

Options Object

  • ignoreKeys: Array of store property keys to exclude from persistence

    Use this for sensitive data or temporary state that doesn't need persistence. Supports both flat keys and dot-notation paths for nested properties at any depth.

            
    // Flat keys — exclude top-level properties
    ignoreKeys: ["password", "token"]
    
    // Nested keys — exclude properties inside objects (dot notation)
    ignoreKeys: ["auth.password", "auth.token"]
    
    // Deeply nested — works at any depth
    ignoreKeys: ["config.api.secretKey", "config.api.privateToken"]
    
    // Mixed — combine flat and nested freely
    ignoreKeys: [
      "sessionToken",           // flat
      "auth.password",          // nested
      "config.api.secretKey"    // deeply nested
    ]
            
          

    Ignored keys are set to undefined in the persisted value. Sibling and parent keys are never affected — only the exact path specified is omitted.

  • timeout: expiration of the stored state, in milliseconds

    Counted again after each write. It is not a time limit of the operation: after it, the stored state is gone (the store keeps what it holds in memory). If not set, the state is kept until removed. A change of an ignoreKeys key alone writes nothing, so it does not renew it.

            
    timeout: 3600000  // expires after 1 hour
    timeout: 86400000 // expires after 24 hours
    timeout: 300000   // expires after 5 minutes
            
          
  • syncTabs: Boolean flag to enable cross-tab synchronization

    When true, changes made in one browser tab will be reflected in all others in real time. Requires channelName and enableSyncTabs: true on the storage adapter — without both, nothing is synced and nothing warns you. Only a state newer than the store's is applied — every write has a revision, so an older state never undoes a newer change; two tabs changing the store at once end with the same state, the one stored (with localStorage, the tab of the newer change writes it again). With IndexedDB and localStorage, a tab shown again reads storage again.

            
    // Enable tab sync
    startStoragefy({
      dbName: "my-app",
      channelName: "storagefy-sync", // 1. the channel the tabs talk on
      enableSyncTabs: true            // 2. this storage tells the other tabs about its writes
    });
    
    await setInStorage(myStore, "user", {
      syncTabs: true
    });
            
          
  • onError: called with an Error when the state could not be saved

    The storage is full, the encryption failed, or a change from another tab could not be read — the store keeps working. getFromStorage(store, key, { onError }) also tells a stored state that is there but cannot be read (another password, changed by hand). A mistake of the app throws instead, so it shows while developing: setInStorage rejects when its first write threw (a storage adapter of your own whose set throws, a state that cannot be copied).

            
    await setInStorage(myStore, "user", {
      onError: (error) => reportToMyApp(error) // error.cause holds what failed
    });
            
          

7. Cross-Tab Synchronization

The React adapter supports real-time synchronization of state across multiple browser tabs:

        
// Initialize with channel name for cross-tab communication
startStoragefy({
  dbName: "my-react-app",
  adapter: "indexedDB",
  channelName: "react-sync",  // the channel the tabs talk on…
  enableSyncTabs: true   // …and this storage tells them about its writes
});

// Enable syncTabs in your store configuration
await setReactStorage(store, "shared-state", {
  syncTabs: true
});

// Now changes to this store in one tab will be reflected in other tabs
        
      

The synchronization uses the BroadcastChannel API under the hood and intelligently handles different store types to apply updates appropriately.

8. API Reference

getReactAdapter([options])

Returns a configured React adapter instance. Options include:

  • adapterParams: Configuration for the underlying storage adapter

Returns: { setInStorage, getFromStorage } methods

setReactStorage(store, key, [options])

Helper function that internally calls getFromStorage followed by setInStorage.

  • store: React state store instance (Redux, Zustand, etc.)
  • key: Storage key string
  • options: Configuration options (ignoreKeys, timeout, syncTabs, onError)

Returns: Promise resolving to true on success

ReactAdapter Class Methods

  • setInStorage(store, key, options): Persists store state and sets up subscription
  • getFromStorage(store, key): Loads persisted state into store — { onError } tells a stored state that cannot be read
  • flush([key]): Makes sure the state is in storage — what the store holds now is written, unless it is stored already, and the promise resolves once its writes are done: true stored,false a write was not saved (onError says why). It never rejects for a write. Without key, every store of the adapter; a key no store is kept under rejects. A store withsubscribe alone cannot be read: flush writes nothing of its own for it and waits for its writes in progress. Call it before something that must not lose a change, such as signing out
  • destroy(key): Stops keeping the store of key — no more writes, no more changes from the other tabs. What is stored stays
  • destroyAll(): Stops keeping every store of the adapter. The storage adapter goes on
  • What the store holds is written and loaded back as it was — any JSON value (an object, an array, a number, a string, a boolean). A state set to null or undefined removes the stored key (a store emptied on sign-out is not loaded back)
  • The state is read with getState() (Redux, Zustand) or get(); a store with neither is read from what it passes its listeners — a notification that passes nothing writes nothing

9. Best Practices

  • Always call getFromStorage before setInStorage to hydrate your store with existing data
  • Before signing out (or anything that must not lose a change), clear the store and await flush(key): once it resolves, the cleared state is in storage and the page may close
  • For Redux stores, ensure your reducer handles the SET_STATE_FROM_STORAGE action type
  • Use ignoreKeys for sensitive information, temporary UI state, or large objects
  • Set appropriate timeout values based on the nature of your data
  • When using syncTabs, be mindful of complex state mutations that could conflict across tabs
  • Call destroy(key) on the React adapter when a store is no longer kept (e.g. its component unmounts) — it stops the writes and the changes from other tabs
  • Consider using separate storage keys for different logical parts of your application state