From 92d631e7ec89308f88deaf2caf7b31682f54277b Mon Sep 17 00:00:00 2001 From: Emanuel Vollmer Date: Mon, 10 Jun 2024 16:11:41 +0200 Subject: [PATCH] Fix useLocalStorage batch updates not working --- index.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index f6e4fe2..a8787af 100644 --- a/index.js +++ b/index.js @@ -614,7 +614,7 @@ const getLocalStorageServerSnapshot = () => { }; export function useLocalStorage(key, initialValue) { - const getSnapshot = () => getLocalStorageItem(key); + const getSnapshot = React.useCallback(() => getLocalStorageItem(key), [key]); const store = React.useSyncExternalStore( useLocalStorageSubscribe, @@ -625,7 +625,7 @@ export function useLocalStorage(key, initialValue) { const setState = React.useCallback( (v) => { try { - const nextState = typeof v === "function" ? v(JSON.parse(store)) : v; + const nextState = typeof v === "function" ? v(JSON.parse(getSnapshot())) : v; if (nextState === undefined || nextState === null) { removeLocalStorageItem(key); @@ -636,7 +636,7 @@ export function useLocalStorage(key, initialValue) { console.warn(e); } }, - [key, store] + [key, getSnapshot] ); React.useEffect(() => {