Skip to content

Commit 3e548e4

Browse files
authored
Initialize hash on mount and improve navigation handling (#3774)
1 parent 3aea302 commit 3e548e4

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

packages/gitbook/src/components/hooks/useHash.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ export const NavigationStatusProvider: React.FC<React.PropsWithChildren> = ({ ch
5151

5252
// Cleanup timeout on unmount
5353
React.useEffect(() => {
54+
// Initialize hash on mount - It could be null on SSR rehydration
55+
setHash(getHash());
5456
return () => {
5557
if (timeoutRef.current) {
5658
clearTimeout(timeoutRef.current);
@@ -73,7 +75,8 @@ export const NavigationStatusProvider: React.FC<React.PropsWithChildren> = ({ ch
7375
if (timeoutRef.current) {
7476
clearTimeout(timeoutRef.current);
7577
}
76-
if (pathnameRef.current !== url.pathname) {
78+
// We don't want to set isNavigating for same page hash navigation
79+
if (pathnameRef.current !== url.pathname && !href.startsWith('#')) {
7780
timeoutRef.current = window.setTimeout(() => {
7881
setIsNavigating(true);
7982
timeoutRef.current = null;
@@ -94,7 +97,7 @@ export const NavigationStatusProvider: React.FC<React.PropsWithChildren> = ({ ch
9497
};
9598

9699
/**
97-
* Hook to get the current hash from the URL.
100+
* Hook to get the current hash from the URL. The hash is set on navigation clicks **NOT** on hashchange events or on navigation end.
98101
* @see https://github.com/vercel/next.js/discussions/49465
99102
* We use a different hack than this one, because for same page link it don't work
100103
* We can't use the `hashChange` event because it doesn't fire for `replaceState` and `pushState` which are used by Next.js.

packages/gitbook/src/components/hooks/useScrollPage.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
'use client';
22

3-
import { usePathname } from 'next/navigation';
43
import React from 'react';
54

65
import { useHash } from './useHash';
@@ -13,8 +12,7 @@ import { usePrevious } from './usePrevious';
1312
export function useScrollPage() {
1413
const hash = useHash();
1514
const previousHash = usePrevious(hash);
16-
const pathname = usePathname();
17-
// biome-ignore lint/correctness/useExhaustiveDependencies: pathname should trigger it.
15+
1816
React.useEffect(() => {
1917
if (hash) {
2018
if (previousHash !== undefined && previousHash !== hash) {
@@ -30,5 +28,5 @@ export function useScrollPage() {
3028
}
3129

3230
window.scrollTo(0, 0);
33-
}, [hash, previousHash, pathname]);
31+
}, [hash, previousHash]);
3432
}

0 commit comments

Comments
 (0)