Skip to content

Commit

Permalink
feat(dequal): state of usePersistedState is now memoized
Browse files Browse the repository at this point in the history
  • Loading branch information
Dennis Morello committed Nov 9, 2020
1 parent 5652099 commit cd02ed9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
15 changes: 15 additions & 0 deletions src/useMemoizedObject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useRef } from 'react';
import { dequal } from 'dequal/lite';

const useMemoizedObject = (obj) => {
const mem = useRef();

if (dequal(mem.current, obj)) {
return mem.current;
}

mem.current = obj;
return obj;
};

export default useMemoizedObject;
21 changes: 10 additions & 11 deletions src/usePersistedState.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { dequal } from 'dequal/lite';
import useEventListener from '@use-it/event-listener';

import createGlobalState from './createGlobalState';
import useMemoizedObject from './useMemoizedObject';

const usePersistedState = (initialState, key, { get, set }) => {
const globalState = useRef(null);
const [state, setState] = useState(() => get(key, initialState));
const [_state, setState] = useState(() => get(key, initialState));
const state = useMemoizedObject(_state);

// subscribe to `storage` change events
useEventListener('storage', ({ key: k, newValue }) => {
Expand All @@ -29,16 +31,13 @@ const usePersistedState = (initialState, key, { get, set }) => {
}, []);

// Only persist to storage if state changes.
useEffect(
() => {
// persist to localStorage
set(key, state);

// inform all of the other instances in this tab
globalState.current.emit(state);
},
[state]
);
useEffect(() => {
// persist to localStorage
set(key, state);

// inform all of the other instances in this tab
globalState.current.emit(state);
}, [state]);

return [state, setState];
};
Expand Down

0 comments on commit cd02ed9

Please sign in to comment.