useLocalStorage/useLocalStorage.ts

usehooks-ts · packages/usehooks-ts/src/useLocalStorage/useLocalStorage.ts · typescript · MIT
ui

Persist React state in local storage, handling SSR and serialization.

// Source: https://github.com/juliencrn/usehooks-ts | License: MIT | Copyright 2020 Julien CARON
// Provided via justclaw.it.com; keep this notice with the code.
import { useCallback, useEffect, useState } from 'react'

import type { Dispatch, SetStateAction } from 'react'

import { useEventCallback } from '../useEventCallback'
import { useEventListener } from '../useEventListener'

declare global {
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
  interface WindowEventMap {
    'local-storage': CustomEvent
  }
}

/**
 * Options for customizing the behavior of serialization and deserialization.
 * @template T - The type of the state to be stored in local storage.
 */
type UseLocalStorageOptions<T> = {
  /** A function to serialize the value before storing it. *

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key