Skip to content

Commit eb0b1eb

Browse files
committed
useLocaStorage: return memoized result
JSON.parse will create a new object on every render cycle
1 parent 945436d commit eb0b1eb

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

index.js

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -639,16 +639,22 @@ export function useLocalStorage(key, initialValue) {
639639
[key, store]
640640
);
641641

642+
const initialValueRef = React.useRef(initialValue);
643+
642644
React.useEffect(() => {
643645
if (
644646
getLocalStorageItem(key) === null &&
645-
typeof initialValue !== "undefined"
647+
typeof initialValueRef.current !== "undefined"
646648
) {
647-
setLocalStorageItem(key, initialValue);
649+
setLocalStorageItem(key, initialValueRef.current);
648650
}
649-
}, [key, initialValue]);
651+
}, [key]);
652+
653+
const result = React.useMemo(() => {
654+
return store ? JSON.parse(store) : initialValueRef.current;
655+
}, [store]);
650656

651-
return [store ? JSON.parse(store) : initialValue, setState];
657+
return [result, setState];
652658
}
653659

654660
export function useLockBodyScroll() {
@@ -1200,16 +1206,22 @@ export function useSessionStorage(key, initialValue) {
12001206
[key, store]
12011207
);
12021208

1209+
const initialValueRef = React.useRef(initialValue);
1210+
12031211
React.useEffect(() => {
12041212
if (
12051213
getSessionStorageItem(key) === null &&
1206-
typeof initialValue !== "undefined"
1214+
typeof initialValueRef.current !== "undefined"
12071215
) {
1208-
setSessionStorageItem(key, initialValue);
1216+
setSessionStorageItem(key, initialValueRef.current);
12091217
}
1210-
}, [key, initialValue]);
1218+
}, [key]);
1219+
1220+
const result = React.useMemo(() => {
1221+
return store ? JSON.parse(store) : initialValueRef.current;
1222+
}, [store]);
12111223

1212-
return [store ? JSON.parse(store) : initialValue, setState];
1224+
return [result, setState];
12131225
}
12141226

12151227
export function useSet(values) {

0 commit comments

Comments
 (0)