From 3f1511d6450eeb59821151b0a821ca41264517c7 Mon Sep 17 00:00:00 2001 From: SukkaW Date: Mon, 25 Nov 2024 20:44:58 +0800 Subject: [PATCH] refactor(use-next-link): adopt `useComponentWillReceiveUpdate` --- src/use-next-link/index.ts | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/use-next-link/index.ts b/src/use-next-link/index.ts index d9c6dabb..ef1e4b84 100644 --- a/src/use-next-link/index.ts +++ b/src/use-next-link/index.ts @@ -1,11 +1,12 @@ import 'client-only'; import type { LinkProps } from 'next/link'; -import { useEffect, useMemo, useState, useTransition, useCallback } from 'react'; +import { useEffect, useMemo, useTransition, useCallback } from 'react'; import { useRouter } from 'next/navigation'; import { formatUrl } from 'next/dist/shared/lib/router/utils/format-url'; import { useIntersection } from '../use-intersection'; +import { useComponentWillReceiveUpdate } from '../use-component-will-receive-update'; import type { PrefetchOptions as AppRouterPrefetchOptions @@ -118,15 +119,7 @@ function useNextLink(hrefProp: string | UrlObject, }), [])); const resolvedHref = useMemo(() => (typeof hrefProp === 'string' ? hrefProp : formatUrl(hrefProp)), [hrefProp]); - const [previousResolvedHref, setPreviousResolvedHref] = useState(resolvedHref); - - if (previousResolvedHref !== resolvedHref) { - // It is safe to set the state during render, as long as it won't trigger an infinite render loop. - // React will render the component with the current state, then throws away the render result - // and immediately re-executes the component function with the updated state. - setPreviousResolvedHref(resolvedHref); - resetVisible(); - } + useComponentWillReceiveUpdate(resetVisible, [resolvedHref]); // Prefetch the URL if we haven't already and it's visible. useEffect(() => {