useStorageState
useStorageState is 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,
refreshState: () => 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 (
localStorageorsessionStorage). Defaults tolocalStorage. - options.defaultValueT
The initial value if no existing value is found.
- options.serializerFunction
A function to serialize the state value to a string.
- options.deserializerFunction
A function to deserialize the state value from a string.
- options.storageStorage · localStorage
Return Value
- readonly [state: Serializable<T> | undefined, setState: (value: SetStateAction<Serializable<T> | undefined>) => void, refreshState: () => 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.
- refreshState() => void
A function to refresh the state from storage.
- 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>
);
}