@technobuddha > react-hooks > React > Hooks
Function: useLocalStorage()
ts
function useLocalStorage<T>(key: string, initialState: T | () => T): readonly [T, (newValue: T | (oldValue: T) => T) => void];Defined in: use-local-storage.ts:35
Similar to React.useState, returns a stateful value and a function to update it. The state value is also saved in localStorage.
Only values that are valid JsonValue (from type-fest) are supported, as all values are serialized with JSON.stringify.
When initializing, if the key exists in localStorage, the stored value is used. Otherwise, the initialState value is used.
Type Parameters
| Type Parameter |
|---|
T extends JsonValue |
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The keyname to use for storing the value in localStorage. |
initialState | T | () => T | Initial state value or a function returning the initial state. |
Returns
readonly [T, (newValue: T | (oldValue: T) => T) => void]
[ stateValue, setterFunction ].
Example
typescript
function Counter() {
const [count, setCount] = useLocalStorage('count', 0);
return (
<div>
<div>Count: {'{'}count{'}'}</div>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}