API Reference
useSessionStorage

useSessionStorage

The useSessionStorage() hook provides a convenient way to manage data persistence in the browser's session 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 useSessionStorage into your component.

import { useSessionStorage } from '@ridgehkr/useful'

Example

This is a simple example of how to store a user's name in session 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.

SessionStorageManager.tsx
import { useState } from 'react'
import { useSessionStorage } from '@ridgehkr/useful'
 
function SessionStorageManager() {
  const [name, setName] = useState('')
  const { value, setStoredValue, deleteStoredValue } =
    useSessionStorage<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

useSessionStorage(key: string, initialValue: T)

Parameters

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

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

Return Value

useSessionStorage returns an object with the following properties:

PropertyTypeDescription
valueTThe current value stored in session 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