DEMO
State - Hello World

useLocalStorage

Modified useState hook that syncs with localStorage.

Usage

import { useLocalStorage } from '@react-hooks-library/core'

export function Demo() {
  const [value, setValue] = useLocalStorage(
    'useLocalsStorageKey',
    'Hello World'
  )

  return (
    <div>
      <div>State - {value}</div>
      <label htmlFor="demo">
        Enter some text to update state and localStorage
      </label>
      <input onChange={(e) => setValue(e.target.value)} type="text" id="demo" />
    </div>
  )
}

Using custom serialize and deserialize options

The default for serialize is JSON.stringify and the default for deserialize is JSON.parse.

const [value, setValue] = useLocalStorage('key', 'value', {
  serialize: JSON.stringify,
  deserialize: JSON.parse
})

Type Declarations

declare type UseLocalStorageOptions = {
  /**
   * Function for converting to string.
   *
   * @default JSON.stringify
   */
  serialize: (value: unknown) => string
  /**
   * Function to convert stored string to object value.
   *
   * @default JSON.parse
   */
  deserialize: (value: string) => unknown
}
/**
 * Modified `useState` hook that syncs with localStorage.
 *
 * @param key
 * @param initialValue
 * @param options
 *
 * @see https://react-hooks-library.vercel.app/core/useLocalStorage
 */
declare function useLocalStorage<T>(
  key: string,
  initialValue: T,
  options?: UseLocalStorageOptions
): [T, (value: T) => void]

Source

Source | Demo | Docs