useStorageState
A React hook that functions like useState
but persists the state value in browser storage. The value is retained across page reloads and can be shared between tabs when using localStorage
.
Interface
ts
function useStorageState(
key: string,
options: Object
): readonly [
state: Serializable<T> | undefined,
setState: (value: SetStateAction<Serializable<T> | undefined>) => void,
];
Parameters
- keyrequired · string
The key used to store the value in storage.
- optionsObject
Configuration options for storage behavior.
- options.storageStorage · localStorage
The storage type (
localStorage
orsessionStorage
). Defaults tolocalStorage
. - options.defaultValueT
The initial value if no existing value is found.
- options.storageStorage · localStorage
Return Value
- readonly [state: Serializable<T> | undefined, setState: (value: SetStateAction<Serializable<T> | undefined>) => void]
tuple:
- stateSerializable<T> | undefined
The current state value retrieved from storage.
- setState(value: SetStateAction<Serializable<T> | undefined>) => void
A function to update and persist the state.
- stateSerializable<T> | undefined
Example
tsx
// Counter with persistent state
import { useStorageState } from 'react-simplikit';
function Counter() {
const [count, setCount] = useStorageState<number>('counter', {
defaultValue: 0,
});
return (
<button onClick={() => setCount(prev => prev + 1)}>Count: {count}</button>
);
}