diff --git a/src/use-url-hash-state/index.ts b/src/use-url-hash-state/index.ts index f7e5db2a..840fac60 100644 --- a/src/use-url-hash-state/index.ts +++ b/src/use-url-hash-state/index.ts @@ -39,16 +39,16 @@ const subscribe: Parameters[0] = (() => { // eslint-disable-next-line @typescript-eslint/ban-types -- workaround TypeScript bug const isFunction = (x: unknown): x is Function => typeof x === 'function'; -function useUrlHashState( +function useUrlHashState( key: string, defaultValue?: undefined ): readonly [T | undefined, React.Dispatch>]; -function useUrlHashState( +function useUrlHashState( key: string, defaultValue: T, transform?: (value: string) => T ): readonly [T, React.Dispatch>]; -function useUrlHashState( +function useUrlHashState( key: string, defaultValue?: T | undefined, transform: (value: string) => T = identity @@ -66,10 +66,10 @@ function useUrlHashState( () => defaultValue ), useCallback((updater) => { - const searchParams = new URLSearchParams(location.hash.slice(1)); - const currentHash = location.hash; + const searchParams = new URLSearchParams(currentHash.slice(1)); + let newValue; if (isFunction(updater)) { @@ -80,7 +80,7 @@ function useUrlHashState( } if ( - (defaultValue !== undefined && newValue === defaultValue) + newValue === defaultValue || newValue === undefined ) { searchParams.delete(key); @@ -94,7 +94,7 @@ function useUrlHashState( return; } - location.hash = searchParams.toString(); + location.hash = newHash; }, [defaultValue, key, memoized_transform]) ] as const; }