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
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
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.
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.
Property | Type | Required | Description |
---|---|---|---|
key | string | yes | The unique identifier of the local storage value |
initialValue | T | no | The initial value |
Return Value
useLocalStorage
returns a LocalStorageState<T>
object with the following properties:
Property | Type | Description |
---|---|---|
value | T | The current value stored in local 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 |