API Reference
useLocalStorage

useLocalStorage

The useLocalStorage hook provides a convenient way to manage data persistence in the browser's local storage. This can be particularly useful for maintaining user preferences or storing small pieces of data that need to persist across sessions.

Usage

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useLocalStorage into your component.

import { useLocalStorage } from '@ridgehkr/useful'

Example

This is a simple example of how to store a user's name in local storage. The name is then retrieved and displayed in a greeting. See the API Reference for more details on the return value of the hook.

UserGreeting.tsx
import { useState } from 'react'
import { useLocalStorage } from '@ridgehkr/useful'
 
function UserGreeting() {
  const [name, setName] = useState('')
  const { value, setStoredValue, deleteStoredValue } = useLocalStorage<string>(
    'user_name',
    ''
  )
 
  const handleNameChange = (value: string) => {
    setName(value)
    setStoredValue(value)
  }
 
  return (
    <div>
      <h1>Hello, {value || 'stranger'}!</h1>
      <input
        type='text'
        value={name}
        onChange={(e) => handleNameChange(e.target.value)}
        placeholder='Enter your name'
      />
      <button onClick={deleteStoredValue}>Clear Name</button>
    </div>
  )
}

API Reference

Hook Signature

useLocalStorage(key: string, initialValue: T): LocalStorageState<T>

Parameters

The useLocalStorage hook takes two parameters: key and initialValue. The key is a unique identifier for the stored value in local storage, while initialValue is the default value to use if no stored value is found.

PropertyTypeRequiredDescription
keystringyesThe unique identifier of the local storage value
initialValueTnoThe initial value

Return Value

useLocalStorage returns a LocalStorageState<T> object with the following properties:

PropertyTypeDescription
valueTThe current value stored in local storage for the provided key
setStoredValue(newValue: T) => voidUpdate the stored value for the provided key
deleteStoredValue() => voidDelete the stored value for the provided key and reset it to the initial value