Skip to content

Commit 1280c7f

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

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

index.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,16 +1200,22 @@ export function useSessionStorage(key, initialValue) {
12001200
[key, store]
12011201
);
12021202

1203+
const initialValueRef = useRef(initialValue)
1204+
12031205
React.useEffect(() => {
12041206
if (
12051207
getSessionStorageItem(key) === null &&
12061208
typeof initialValue !== "undefined"
12071209
) {
1208-
setSessionStorageItem(key, initialValue);
1210+
setSessionStorageItem(key, initialValueRef.current);
12091211
}
1210-
}, [key, initialValue]);
1212+
}, [key]);
12111213

1212-
return [store ? JSON.parse(store) : initialValue, setState];
1214+
const result = useMemo(() => {
1215+
return store ? JSON.parse(store) : initialValueRef.current
1216+
}, [store])
1217+
1218+
return [result, setState];
12131219
}
12141220

12151221
export function useSet(values) {

0 commit comments

Comments
 (0)