@consumidor-positivo/ts-utils - v1.13.0
    Preparing search index...

    Function usePersistedState

    • A hook that manages persistent state in localStorage or sessionStorage.

      This hook allows storing any type of data (primitives, objects, arrays) by converting them to JSON when saving and reconstituting them when retrieving.

      Type Parameters

      • T

      Parameters

      • storageKey: string

        Key used to store data in storage

      • OptionalinitialState: T

        Initial state value (optional)

      • options: UsePersistedStateOptions = {}

        Configuration options

      Returns readonly [null | T, (newValue: T) => void, () => void]

      A tuple containing [current state, function to update state, function to clear state]

      import { usePersistedState } from '@consumidor-positivo/ts-utils/hooks';

      function UserPreferences() {
      // Persistent state with initial value using localStorage (default)
      const [preferences, setPreferences, clearPreferences] = usePersistedState('user-preferences', {
      theme: 'light',
      fontSize: 14
      });

      // Persistent state using sessionStorage
      const [sessionInfo, setSessionInfo] = usePersistedState('session-info', { isLoggedIn: true }, { storage: 'session' });

      return (
      <div>
      <h1>User preferences: {preferences?.theme}</h1>
      <button onClick={() => setPreferences({ ...preferences, theme: 'dark' })}>
      Change theme
      </button>
      <button onClick={clearPreferences}>Clear preferences</button>
      </div>
      );
      }