From b2310e105cab03f5ff42d25b3d4c3dd6ab2dbd97 Mon Sep 17 00:00:00 2001 From: Hunter Wilhelm Date: Sun, 4 Dec 2022 04:44:19 -0700 Subject: [PATCH] [@mantine/hooks] use-hash: Fix unexpected rerendering with hash without `#` (#3097) * Fix use-hash extra rerendering issue Two bugs fixed: * If you `setHash` to something that doesn't start with "#" it would be reflect that temporarily in `hash` * `setHashValue` was being called multiple times (one in the listener and the set hash) resulting in the multiple renders Result: * `setHash` only rerenders the page once. * Fix tests window is not defined in ssr * fix formatting * Fix no-param-reassign and prefer-template --- src/mantine-hooks/src/use-hash/use-hash.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/mantine-hooks/src/use-hash/use-hash.ts b/src/mantine-hooks/src/use-hash/use-hash.ts index 264dfb04bdb..4436f269bdc 100644 --- a/src/mantine-hooks/src/use-hash/use-hash.ts +++ b/src/mantine-hooks/src/use-hash/use-hash.ts @@ -5,16 +5,20 @@ export function useHash() { const [hash, setHashValue] = useState(''); const setHash = (value: string) => { - window.location.hash = value; - setHashValue(value); + const valueWithHash = value.startsWith('#') ? value : `#${value}`; + window.location.hash = valueWithHash; + setHashValue(valueWithHash); }; useWindowEvent('hashchange', () => { - setHashValue(window.location.hash); + const newHash = window.location.hash; + if (hash !== newHash) { + setHashValue(hash); + } }); useEffect(() => { - setHash(window.location.hash); + setHashValue(window.location.hash); }, []); return [hash, setHash] as const;