Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/useSessionStorage.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

React side-effect hook that manages a single `sessionStorage` key.

Each hook instance maintains its own state. When instances share a key, changing one
instance's value persists that value; rerendering an instance whose state is unchanged
leaves the stored value intact.


## Usage

Expand Down
2 changes: 1 addition & 1 deletion src/useSessionStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const useSessionStorage = <T>(
// If user is in private mode or has storage restriction
// sessionStorage can throw. Also JSON.stringify can throw.
}
});
}, [key, raw, state]);

return [state, setState];
};
Expand Down
14 changes: 14 additions & 0 deletions tests/useSessionStorage.server.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import useSessionStorage from '../src/useSessionStorage';

jest.mock('../src/misc/util', () => ({
isBrowser: false,
}));

describe('useSessionStorage on the server', () => {
it('returns the initial value and a safe state setter', () => {
const [value, setValue] = useSessionStorage('value', 'initial');

expect(value).toBe('initial');
expect(setValue('updated')).toBeUndefined();
});
});
89 changes: 89 additions & 0 deletions tests/useSessionStorage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { act, renderHook } from '@testing-library/react-hooks';
import useSessionStorage from '../src/useSessionStorage';

describe('useSessionStorage', () => {
afterEach(() => {
sessionStorage.clear();
jest.clearAllMocks();
});

it.each([false, true])(
'preserves updates when multiple instances share a key with raw=%s',
(raw) => {
const { result, rerender } = renderHook(() => ({
first: useSessionStorage('shared', 'initial', raw),
second: useSessionStorage('shared', 'initial', raw),
}));

act(() => result.current.first[1]('updated'));

expect(result.current.first[0]).toBe('updated');
expect(result.current.second[0]).toBe('initial');
expect(sessionStorage.getItem('shared')).toBe(raw ? 'updated' : '"updated"');

rerender();

expect(sessionStorage.getItem('shared')).toBe(raw ? 'updated' : '"updated"');
}
);

it('does not persist unchanged state on unrelated rerenders', () => {
const { rerender } = renderHook(() => useSessionStorage('value', 'initial'));
(sessionStorage.setItem as jest.Mock).mockClear();

rerender();

expect(sessionStorage.setItem).not.toHaveBeenCalled();
});

it('persists the current state under a new key', () => {
const { result, rerender } = renderHook(({ key }) => useSessionStorage(key, 'initial'), {
initialProps: { key: 'first' },
});

act(() => result.current[1]('updated'));
rerender({ key: 'second' });

expect(result.current[0]).toBe('updated');
expect(sessionStorage.getItem('first')).toBe('"updated"');
expect(sessionStorage.getItem('second')).toBe('"updated"');
});

it('persists the current state when the serialization mode changes', () => {
const { result, rerender } = renderHook(
({ raw }) => useSessionStorage('value', 'initial', raw),
{
initialProps: { raw: false },
}
);

act(() => result.current[1]('updated'));
rerender({ raw: true });
expect(sessionStorage.getItem('value')).toBe('updated');

rerender({ raw: false });
expect(sessionStorage.getItem('value')).toBe('"updated"');
});

it('keeps the initial state when session storage access is restricted', () => {
(sessionStorage.getItem as jest.Mock).mockImplementationOnce(() => {
throw new Error('Storage access denied');
});
(sessionStorage.setItem as jest.Mock).mockImplementationOnce(() => {
throw new Error('Storage access denied');
});

const { result } = renderHook(() => useSessionStorage('value', 'initial'));

expect(result.current[0]).toBe('initial');
expect(result.error).toBeUndefined();
});

it('treats an empty serialized value as null', () => {
(sessionStorage.getItem as jest.Mock).mockReturnValueOnce('');

const { result } = renderHook(() => useSessionStorage('value', 'initial'));

expect(result.current[0]).toBeNull();
});
});