DEMO
State - Hello World
useSessionStorage
Modified useState
hook that syncs with sessionStorage.
Usage
import { useSessionStorage } from '@react-hooks-library/core'
export function Demo() {
const [value, setValue] = useSessionStorage(
'useSessionStorageKey',
'Hello World'
)
return (
<div>
<div>State - {value}</div>
<label htmlFor="demo">
Enter some text to update state and sessionStorage
</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] = useSessionStorage('key', 'value', {
serialize: JSON.stringify,
deserialize: JSON.parse
})
Type Declarations
declare type UseSessionStorageOptions = {
/**
* 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 useSessionStorage.
*
* @param key
* @param initialValue
* @param options
*
* @see https://react-hooks-library.vercel.app/core/useSessionStorage
*/
declare function useSessionStorage<T>(
key: string,
initialValue: T,
options?: UseSessionStorageOptions
): [T, (value: T) => void]