Skip to content

useStorageState ​

useStorageState is a React 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<T>(
  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 (localStorage or sessionStorage). Defaults to localStorage.

    • 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.

Return Value ​

  • readonly [state: Serializable<T> | undefined, setState: (value: SetStateAction<Serializable<T> | undefined>) => void, refreshState: () => void]

    A 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.

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>
  );
}

Released under the MIT License.