Skip to content

@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

ParameterTypeDescription
keystringThe keyname to use for storing the value in localStorage.
initialStateT | () => TInitial 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>
  );
}