Skip to content

Commit

Permalink
fix(useLocalStorage): reinitialize on key change
Browse files Browse the repository at this point in the history
  • Loading branch information
adesurirey committed Apr 14, 2021
1 parent a91c1f1 commit fdd1b23
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Dispatch, SetStateAction, useCallback, useState } from 'react';
import { Dispatch, SetStateAction, useCallback, useState, useRef, useLayoutEffect } from 'react';
import { isBrowser, noop } from './misc/util';

type parserOptions<T> =
Expand Down Expand Up @@ -30,7 +30,7 @@ const useLocalStorage = <T>(
: JSON.parse;

// eslint-disable-next-line react-hooks/rules-of-hooks
const [state, setState] = useState<T | undefined>(() => {
const initializer = useRef((key: string) => {
try {
const serializer = options ? (options.raw ? String : options.serializer) : JSON.stringify;

Expand All @@ -49,6 +49,12 @@ const useLocalStorage = <T>(
}
});

// eslint-disable-next-line react-hooks/rules-of-hooks
const [state, setState] = useState<T | undefined>(() => initializer.current(key));

// eslint-disable-next-line react-hooks/rules-of-hooks
useLayoutEffect(() => setState(initializer.current(key)), [key]);

// eslint-disable-next-line react-hooks/rules-of-hooks
const set: Dispatch<SetStateAction<T | undefined>> = useCallback(
(valOrFunc) => {
Expand Down
13 changes: 13 additions & 0 deletions tests/useLocalStorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,19 @@ describe(useLocalStorage, () => {
expect(foo).toEqual('baz');
});

it('reinitializes state when key changes', () => {
let key = 'foo';
const { result, rerender } = renderHook(() => useLocalStorage(key, 'bar'));

const [, setState] = result.current;
act(() => setState('baz'));
key = 'bar';
rerender();

const [state] = result.current;
expect(state).toEqual('bar');
});

/*
it('keeps multiple hooks accessing the same key in sync', () => {
localStorage.setItem('foo', 'bar');
Expand Down

0 comments on commit fdd1b23

Please sign in to comment.