Skip to main content

useSessionStorage

A custom hook that leverages useSyncExternalStore (supported from React v18) to subscribe to a specific key in session storage and synchronize the subscribed data whenever it changes.

You can set an initialValue to return when the subscribed key does not exist in session storage. In server-side rendering (SSR) environments, session storage is not available, so initialValue is returned.

setState can accept a value directly, or a function. When used as a function, the current state is passed as the argument.

const { state, setState, removeState } = useSessionStorage<number[]>({
key: 'test',
initialValue: [1, 2],
});

setState([1, 2, 3]);
setState(state => [...state, 3]);

Providing an initialValue enables more precise type inference.

const { state, setState } = useSessionStorage<number[]>({
key: 'test',
});

state; // number[] | null
setState(state => {
state; // number[] | null
});
const { state, setState } = useSessionStorage<number[]>({
key: 'test',
initialValue: [],
});

state; // number[]
setState(state => {
state; // number[]
});

Code

🔗 View source code


Interface

typescript
interface UseSessionStorageWithoutInitialValueProps {
key: string;
}

interface UseSessionStorageWithInitialValueProps<T> {
key: string;
initialValue: T | (() => T);
}

type UseSessionStorageProps<T> =
| UseSessionStorageWithoutInitialValueProps
| UseSessionStorageWithInitialValueProps<T>;
typescript
// Function overloading
function useSessionStorage<T>({
key,
initialValue,
}: UseSessionStorageWithInitialValueProps<T>): {
state: T;
setState: Dispatch<SetStateAction<T>>;
removeState: () => void;
};

function useSessionStorage<T = unknown>({
key,
}: UseSessionStorageWithoutInitialValueProps): {
state: T | null;
setState: Dispatch<SetStateAction<T | null>>;
removeState: () => void;
};

Options

NameTypeDefaultDescription
keystring-The key to subscribe to in session storage
initialValueT | (() => T)nullThe initial value to return when the key does not exist or in SSR environments

Returns

NameTypeDescription
stateT or T | nullThe current value from session storage. May be null if no initialValue is provided.
setStateDispatch<SetStateAction<T>>Function to update the session storage value
removeState() => voidFunction to remove the key from session storage

Usage

typescript
import { useSessionStorage } from '@modern-kit/react';

const Example = () => {
const { state, setState, removeState } = useSessionStorage<string>({
key: 'test',
initialValue: 'default',
});

return (
<div>
<p>Check the session storage in your browser's DevTools!</p>
<p>state: {state}</p>
<button onClick={() => setState('foo')}>
{`Save "foo" to session storage key "test"`}
</button>
<button onClick={() => setState('bar')}>
{`Save "bar" to session storage key "test"`}
</button>
<button onClick={() => removeState()}>
{`Remove session storage key "test"`}
</button>
</div>
);
};

Example

Check the session storage in your browser's DevTools!

state: default