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
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
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.
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.
Property | Type | Required | Description |
---|---|---|---|
key | string | yes | The unique identifier of the session storage value |
initialValue | T | no | The initial value |
Return Value
useSessionStorage
returns an object with the following properties:
Property | Type | Description |
---|---|---|
value | T | The current value stored in session storage for the provided key |
setStoredValue | (newValue: T) => void | Update the stored value for the provided key |
deleteStoredValue | () => void | Delete the stored value for the provided key and reset it to the initial value |