Skip to content

Commit 7bc608a

Browse files
committed
fix(site): dispatch global hashchange event on hash update
1 parent c79ec05 commit 7bc608a

1 file changed

Lines changed: 9 additions & 29 deletions

File tree

‎apps/site/hooks/useHash.ts‎

Lines changed: 9 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,23 @@
11
'use client';
22

3-
import { useSyncExternalStore } from 'react';
4-
5-
const listeners = new Set<() => void>();
6-
let isListening = false;
7-
8-
const onHashChange = () => {
9-
listeners.forEach(rerender => rerender());
10-
};
3+
import { useSyncExternalStore, useCallback } from 'react';
114

125
const subscribe = (callback: () => void) => {
13-
listeners.add(callback);
14-
if (!isListening && typeof window !== 'undefined') {
15-
window.addEventListener('hashchange', onHashChange);
16-
isListening = true;
17-
}
18-
return () => {
19-
listeners.delete(callback);
20-
if (listeners.size === 0 && typeof window !== 'undefined') {
21-
window.removeEventListener('hashchange', onHashChange);
22-
isListening = false;
23-
}
24-
};
6+
window.addEventListener('hashchange', callback);
7+
return () => window.removeEventListener('hashchange', callback);
258
};
269

27-
const getSnapshot = () =>
28-
typeof window !== 'undefined' ? window.location.hash.slice(1) : '';
10+
const getSnapshot = () => window.location.hash.slice(1);
2911
const getServerSnapshot = () => '';
3012

3113
const useHash = () => {
32-
// Works in both client and server environments, provides the initial value for the store during server rendering and hydration avoiding hydration mismatches
14+
// Works in both client and server environments, provides the initial value for the store during server rendering and hydration, avoiding hydration mismatches
3315
const hash = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3416

35-
const setHash = (newHash: string) => {
36-
if (typeof window !== 'undefined') {
37-
window.history.replaceState(null, '', `#${newHash}`);
38-
onHashChange();
39-
}
40-
};
17+
const setHash = useCallback((newHash: string) => {
18+
window.history.replaceState(null, '', `#${newHash}`);
19+
window.dispatchEvent(new Event('hashchange'));
20+
}, []);
4121

4222
return [hash, setHash] as const;
4323
};

0 commit comments

Comments
 (0)