All files / use-session-storage/src useSessionStorage.ts

93.33% Statements 56/60
85.71% Branches 18/21
88.88% Functions 8/9
93.33% Lines 56/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281                                                                                        73x                                                                                                                                                                                 92x     92x 92x 92x 92x   92x 92x 92x 92x         92x         92x       92x     54x           54x 54x             92x 322x       322x 322x     322x 252x         70x 28x   42x       64x   64x   6x 6x 6x 6x         92x         92x             92x   33x   33x 33x 33x 33x 11x   22x             33x   33x 33x 33x     33x           33x     1x             92x 3x 3x 3x     3x 3x     3x             92x    
import { useCallback, useRef, useSyncExternalStore } from "react";
import { subscribe, notifyListeners } from "./store";
 
/**
 * Type for initial value that can be a value or a function returning a value (lazy initialization)
 */
export type InitialValue<T> = T | (() => T);
 
/**
 * Options for useSessionStorage hook
 */
export interface UseSessionStorageOptions<T> {
  /**
   * Custom serializer function for converting value to string
   * @default JSON.stringify
   */
  serializer?: (value: T) => string;
  /**
   * Custom deserializer function for parsing stored string to value
   * @default JSON.parse
   */
  deserializer?: (value: string) => T;
  /**
   * Callback function called when an error occurs
   */
  onError?: (error: Error) => void;
}
 
/**
 * Return type for useSessionStorage hook - tuple similar to useState
 */
export type UseSessionStorageReturn<T> = readonly [
  /** Current stored value */
  T,
  /** Function to update the value (same signature as useState setter) */
  React.Dispatch<React.SetStateAction<T>>,
  /** Function to remove the value from sessionStorage */
  () => void
];
 
/**
 * Helper function to resolve initial value (supports lazy initialization)
 */
function resolveInitialValue<T>(initialValue: InitialValue<T>): T {
  return typeof initialValue === "function"
    ? (initialValue as () => T)()
    : initialValue;
}
 
/**
 * A hook for persisting state in sessionStorage with automatic synchronization.
 * Works like useState but persists the value in sessionStorage for the duration of the browser session.
 *
 * Features:
 * - Same-tab synchronization: Multiple components using the same key will stay in sync
 * - SSR compatible: Works with Next.js, Remix, and other SSR frameworks
 *
 * Unlike localStorage, sessionStorage data:
 * - Is cleared when the tab/window is closed
 * - Is not shared between tabs (each tab has its own session)
 *
 * @template T - The type of the stored value
 * @param key - The sessionStorage key to store the value under
 * @param initialValue - Initial value or function returning initial value (lazy initialization)
 * @param options - Configuration options for serialization and error handling
 * @returns A tuple of [storedValue, setValue, removeValue]
 *
 * @example
 * ```tsx
 * // Basic usage - form data that persists during session
 * function CheckoutForm() {
 *   const [formData, setFormData, clearForm] = useSessionStorage('checkout-form', {
 *     name: '',
 *     email: '',
 *   });
 *
 *   return (
 *     <form>
 *       <input
 *         value={formData.name}
 *         onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
 *       />
 *       <button type="button" onClick={clearForm}>Clear</button>
 *     </form>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Same-tab synchronization - both components stay in sync
 * function ComponentA() {
 *   const [step, setStep] = useSessionStorage('wizard-step', 1);
 *   return <button onClick={() => setStep(s => s + 1)}>Next Step</button>;
 * }
 *
 * function ComponentB() {
 *   const [step] = useSessionStorage('wizard-step', 1);
 *   // Automatically updates when ComponentA calls setStep!
 *   return <p>Current Step: {step}</p>;
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Temporary state that resets on tab close
 * const [wizardStep, setWizardStep] = useSessionStorage('wizard-step', 1);
 * ```
 *
 * @example
 * ```tsx
 * // With lazy initialization
 * const [cache, setCache] = useSessionStorage('cache', () => computeInitialCache());
 * ```
 *
 * @example
 * ```tsx
 * // With custom serializer/deserializer
 * const [date, setDate] = useSessionStorage<Date>('lastAction', new Date(), {
 *   serializer: (d) => d.toISOString(),
 *   deserializer: (s) => new Date(s),
 * });
 * ```
 */
export function useSessionStorage<T>(
  key: string,
  initialValue: InitialValue<T>,
  options: UseSessionStorageOptions<T> = {}
): UseSessionStorageReturn<T> {
  const {
    serializer = JSON.stringify,
    deserializer = JSON.parse,
    onError,
  } = options;
 
  // Store options in refs for stable references and access to latest values
  const serializerRef = useRef(serializer);
  const deserializerRef = useRef(deserializer);
  const onErrorRef = useRef(onError);
  const initialValueRef = useRef(initialValue);
 
  serializerRef.current = serializer;
  deserializerRef.current = deserializer;
  onErrorRef.current = onError;
  initialValueRef.current = initialValue;
 
  // Cache for getSnapshot to ensure stable returns and prevent infinite loops
  // useSyncExternalStore requires getSnapshot to return the same reference
  // if the data hasn't changed
  const cacheRef = useRef<{ rawValue: string | null; parsedValue: T } | null>(
    null
  );
 
  // SSR check
  const isClient = typeof window !== "undefined";
 
  // Subscribe function for useSyncExternalStore
  // Handles same-tab synchronization (sessionStorage doesn't have cross-tab sync)
  const subscribeToStore = useCallback(
    (onStoreChange: () => void) => {
      // Subscribe to same-tab changes via internal store
      const unsubscribeStore = subscribe(key, onStoreChange);
 
      // Note: sessionStorage doesn't fire storage events for changes in the same tab,
      // and changes in other tabs don't affect this tab's sessionStorage.
      // So we only use the internal store for synchronization.
 
      return () => {
        unsubscribeStore();
      };
    },
    [key]
  );
 
  // getSnapshot: Read current value from sessionStorage with caching
  const getSnapshot = useCallback((): T => {
    Iif (!isClient) {
      return resolveInitialValue(initialValueRef.current);
    }
 
    try {
      const rawValue = window.sessionStorage.getItem(key);
 
      // Check cache: if rawValue is the same, return cached parsed value
      if (cacheRef.current && cacheRef.current.rawValue === rawValue) {
        return cacheRef.current.parsedValue;
      }
 
      // Parse new value
      let parsedValue: T;
      if (rawValue !== null) {
        parsedValue = deserializerRef.current(rawValue);
      } else {
        parsedValue = resolveInitialValue(initialValueRef.current);
      }
 
      // Update cache
      cacheRef.current = { rawValue, parsedValue };
 
      return parsedValue;
    } catch (error) {
      onErrorRef.current?.(error as Error);
      const fallbackValue = resolveInitialValue(initialValueRef.current);
      cacheRef.current = { rawValue: null, parsedValue: fallbackValue };
      return fallbackValue;
    }
  }, [key, isClient]);
 
  // getServerSnapshot: Return initial value for SSR
  const getServerSnapshot = useCallback((): T => {
    return resolveInitialValue(initialValueRef.current);
  }, []);
 
  // Use useSyncExternalStore for synchronized state
  const storedValue = useSyncExternalStore(
    subscribeToStore,
    getSnapshot,
    getServerSnapshot
  );
 
  // setValue - stable reference that updates sessionStorage and notifies listeners
  const setValue = useCallback<React.Dispatch<React.SetStateAction<T>>>(
    (value) => {
      try {
        // Get current value for functional updates
        const currentValue = (() => {
          try {
            const item = window.sessionStorage.getItem(key);
            if (item !== null) {
              return deserializerRef.current(item);
            }
            return resolveInitialValue(initialValueRef.current);
          } catch {
            return resolveInitialValue(initialValueRef.current);
          }
        })();
 
        const valueToStore =
          value instanceof Function ? value(currentValue) : value;
 
        Eif (typeof window !== "undefined") {
          const serialized = serializerRef.current(valueToStore);
          window.sessionStorage.setItem(key, serialized);
 
          // Invalidate cache so next getSnapshot reads fresh value
          cacheRef.current = {
            rawValue: serialized,
            parsedValue: valueToStore,
          };
 
          // Notify all same-tab listeners
          notifyListeners(key);
        }
      } catch (error) {
        onErrorRef.current?.(error as Error);
      }
    },
    [key]
  );
 
  // removeValue - stable reference
  const removeValue = useCallback(() => {
    try {
      Eif (typeof window !== "undefined") {
        window.sessionStorage.removeItem(key);
 
        // Invalidate cache
        const initialVal = resolveInitialValue(initialValueRef.current);
        cacheRef.current = { rawValue: null, parsedValue: initialVal };
 
        // Notify all same-tab listeners
        notifyListeners(key);
      }
    } catch (error) {
      onErrorRef.current?.(error as Error);
    }
  }, [key]);
 
  return [storedValue, setValue, removeValue] as const;
}