|
1 | 1 | 'use client'; |
2 | 2 |
|
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'; |
11 | 4 |
|
12 | 5 | 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); |
25 | 8 | }; |
26 | 9 |
|
27 | | -const getSnapshot = () => |
28 | | - typeof window !== 'undefined' ? window.location.hash.slice(1) : ''; |
| 10 | +const getSnapshot = () => window.location.hash.slice(1); |
29 | 11 | const getServerSnapshot = () => ''; |
30 | 12 |
|
31 | 13 | 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 |
33 | 15 | const hash = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); |
34 | 16 |
|
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 | + }, []); |
41 | 21 |
|
42 | 22 | return [hash, setHash] as const; |
43 | 23 | }; |
|
0 commit comments