Skip to content

Cache

Caching functionality for persisting Signify state in browser storage.

Description

The cache feature allows Signify state to be automatically persisted in localStorage or sessionStorage. When the application reloads, the state is restored from the cached value instead of using the initial value.

Configuration

PropertyTypeDescription
keystringUnique identifier for the cached value
type'LocalStorage' | 'SesionStorage'Storage type (default: 'LocalStorage')

Input/Output

Storage TypePersistenceDescription
LocalStoragePermanentData persists until manually cleared
SesionStorageSessionData cleared when browser tab closes

Features

  • Automatic Persistence: State is saved automatically on every update
  • Restore on Load: Initial value is loaded from cache if available
  • SSR Safe: Throws helpful error when used in server-side rendering
  • Type Safe: Maintains TypeScript types through serialization

Example

typescript
import { signify } from 'react-signify';
import React from 'react';

// User preferences with localStorage caching
const sUserPreferences = signify(
  { 
    theme: 'light', 
    language: 'en', 
    fontSize: 14 
  },
  {
    cache: {
      key: 'user-preferences',
      type: 'LocalStorage' // Persists across browser sessions
    }
  }
);

// Session data with sessionStorage caching  
const sSessionData = signify(
  { 
    isLoggedIn: false, 
    currentPage: 'home' 
  },
  {
    cache: {
      key: 'session-data',
      type: 'SesionStorage' // Cleared when tab closes
    }
  }
);

function SettingsComponent() {
  const preferences = sUserPreferences.use();
  const session = sSessionData.use();
  
  return (
    <div>
      <h2>Settings</h2>
      
      {/* Theme selector */}
      <label>
        Theme:
        <select 
          value={preferences.theme}
          onChange={(e) => sUserPreferences.set(({ value }) => {
            value.theme = e.target.value;
          })}
        >
          <option value="light">Light</option>
          <option value="dark">Dark</option>
        </select>
      </label>
      
      {/* Font size slider */}
      <label>
        Font Size: {preferences.fontSize}px
        <input 
          type="range"
          min="12"
          max="24"
          value={preferences.fontSize}
          onChange={(e) => sUserPreferences.set(({ value }) => {
            value.fontSize = Number(e.target.value);
          })}
        />
      </label>
      
      <p>Session Status: {session.isLoggedIn ? 'Logged In' : 'Logged Out'}</p>
      
      <button 
        onClick={() => sSessionData.set(({ value }) => {
          value.isLoggedIn = !value.isLoggedIn;
        })}
      >
        Toggle Login
      </button>
    </div>
  );
}

Important Notes:

  • Cache feature is not recommended for Server-Side Rendering
  • Data is automatically serialized/deserialized as JSON
  • Large objects may impact performance due to storage limitations

Released under the MIT License.