From 4f5dcc03360d03b203261348b5809f0bf879ec03 Mon Sep 17 00:00:00 2001 From: en Date: Tue, 11 Mar 2025 10:58:19 +0000 Subject: [PATCH] refactor(hooks): add comments to local storage hook --- src/hooks/useLocalStorage.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/hooks/useLocalStorage.ts b/src/hooks/useLocalStorage.ts index ec6c9cb..a2a9532 100644 --- a/src/hooks/useLocalStorage.ts +++ b/src/hooks/useLocalStorage.ts @@ -6,6 +6,11 @@ import { setLocalStorageItem } from '../utils' +/** + * Subscribe to the Browser's storage event. Get the new value if any of the tabs changes it. + * @param callback - function to be called when the storage event is triggered + * @returns clean up function + */ const useLocalStorageSubscribe = (callback: () => void) => { window.addEventListener('storage', callback) return () => window.removeEventListener('storage', callback) @@ -28,8 +33,11 @@ export function useLocalStorage( ) } + // https://react.dev/reference/react/useSyncExternalStore + // Returns the snapshot of the data and subscribes to the storage event const data = React.useSyncExternalStore(useLocalStorageSubscribe, getSnapshot) + // Takes the value or a function that returns the value and updates the local storage const setState: React.Dispatch> = React.useCallback( (v: React.SetStateAction) => { try {