Skip to content

Commit 9ea70de

Browse files
committed
Avoid hash hydration mismatches
1 parent e5fd630 commit 9ea70de

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/hooks/useLocationHash.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* LICENSE file in the root directory of this source tree.
88
*/
99

10-
import {useSyncExternalStore} from 'react';
10+
import {useEffect, useState} from 'react';
1111

1212
function getHashValue() {
1313
if (typeof window === 'undefined') {
@@ -17,17 +17,20 @@ function getHashValue() {
1717
return window.location.hash.slice(1);
1818
}
1919

20-
function subscribeToHashChange(callback: () => void) {
21-
if (typeof window === 'undefined') {
22-
return () => {};
23-
}
20+
export function useLocationHash() {
21+
const [hash, setHash] = useState('');
2422

25-
window.addEventListener('hashchange', callback);
26-
return () => {
27-
window.removeEventListener('hashchange', callback);
28-
};
29-
}
23+
useEffect(() => {
24+
const updateHash = () => {
25+
setHash(getHashValue());
26+
};
3027

31-
export function useLocationHash() {
32-
return useSyncExternalStore(subscribeToHashChange, getHashValue, () => '');
28+
updateHash();
29+
window.addEventListener('hashchange', updateHash);
30+
return () => {
31+
window.removeEventListener('hashchange', updateHash);
32+
};
33+
}, []);
34+
35+
return hash;
3336
}

0 commit comments

Comments
 (0)