diff --git a/src/hooks/useLocalStorage.tsx b/src/hooks/useLocalStorage.tsx index 4d1eac2..10579cd 100644 --- a/src/hooks/useLocalStorage.tsx +++ b/src/hooks/useLocalStorage.tsx @@ -1,4 +1,4 @@ -import React from 'react' +import React, { useMemo } from 'react' import { getLocalStorageItem, removeLocalStorageItem, @@ -11,7 +11,11 @@ const useLocalStorageSubscribe = (callback: () => void) => { } function mergeWithInitialValue(storedValue: T, initialValue: T): T { - if (typeof storedValue === 'object' && storedValue !== null) { + if ( + !Array.isArray(storedValue) && + typeof storedValue === 'object' && + storedValue !== null + ) { return { ...initialValue, ...storedValue } } return storedValue @@ -64,5 +68,7 @@ export function useLocalStorage( } }, [key, initialValue]) - return [JSON.parse(data) as T, setState] + const memoized = useMemo(() => JSON.parse(data) as T, [data]) + + return [memoized, setState] } diff --git a/src/hooks/useSessionStorage.tsx b/src/hooks/useSessionStorage.tsx index 8f50422..cc0756f 100644 --- a/src/hooks/useSessionStorage.tsx +++ b/src/hooks/useSessionStorage.tsx @@ -1,4 +1,4 @@ -import React from 'react' +import React, { useMemo } from 'react' import { getSessionStorageItem, removeSessionStorageItem, @@ -11,7 +11,11 @@ const useSessionStorageSubscribe = (callback: () => void) => { } function mergeWithInitialValue(storedValue: T, initialValue: T): T { - if (typeof storedValue === 'object' && storedValue !== null) { + if ( + !Array.isArray(storedValue) && + typeof storedValue === 'object' && + storedValue !== null + ) { return { ...initialValue, ...storedValue } } return storedValue @@ -67,5 +71,7 @@ export function useSessionStorage( } }, [key, initialValue]) - return [JSON.parse(data) as T, setState] + const memoized = useMemo(() => JSON.parse(data) as T, [data]) + + return [memoized, setState] }