Skip to content

useSessionStorage()

useSessionStorage<T>(key, initialValue): object

Defined in: src/hooks/state/useSessionStorage.ts:40

A custom React hook for managing state that is synchronized with sessionStorage. Provides error handling by returning a status object along with the value and setter.

Type Parameters

T

Parameters

key

string

The key to store the data under in sessionStorage.

initialValue

T

The initial value to use if no data is stored under the key.

Returns

object

An object containing the stored value, setter function, and error state.

value

value: T

setValue()

setValue: (value) => void

Parameters

value

T | (currentValue) => T

Returns

void

error

error: null | Error

Example

tsx
import { useSessionStorage } from '@zl-asica/react';

const MyComponent = () => {
  const { value: theme, setValue: setTheme, error } = useSessionStorage<string>('theme', 'light');

  if (error) {
    return <p>Error: {error.message}</p>;
  }

  return (
    <div>
      <select value={theme} onChange={(e) => setTheme(e.target.value)}>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
      </select>
      <p>Selected Theme: {theme}</p>
    </div>
  );
};

Released under the MIT License.