From 5d0fc9f786ef522d74333f2dc9384626fd8cad3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D5=A1=D3=84=D5=A1?= Date: Fri, 3 Jan 2025 22:23:42 +0800 Subject: [PATCH] fix(use-image): set status after hydrated (#4486) * fix(use-image): set status after hydrated * fix(use-image): use useSafeLayoutEffect instead --- .changeset/fair-pigs-tap.md | 5 +++++ packages/hooks/use-image/src/index.ts | 11 ++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 .changeset/fair-pigs-tap.md diff --git a/.changeset/fair-pigs-tap.md b/.changeset/fair-pigs-tap.md new file mode 100644 index 0000000000..b026d0a91d --- /dev/null +++ b/.changeset/fair-pigs-tap.md @@ -0,0 +1,5 @@ +--- +"@nextui-org/use-image": patch +--- + +set status after hydrated diff --git a/packages/hooks/use-image/src/index.ts b/packages/hooks/use-image/src/index.ts index 860bc1b7f5..dd47fd99a7 100644 --- a/packages/hooks/use-image/src/index.ts +++ b/packages/hooks/use-image/src/index.ts @@ -6,6 +6,7 @@ import type {ImgHTMLAttributes, SyntheticEvent} from "react"; import {useRef, useState, useEffect, MutableRefObject} from "react"; import {useIsHydrated} from "@nextui-org/react-utils"; +import {useSafeLayoutEffect} from "@nextui-org/use-safe-layout-effect"; type NativeImageProps = ImgHTMLAttributes; @@ -71,9 +72,7 @@ export function useImage(props: UseImageProps = {}) { const imageRef = useRef(isHydrated ? new Image() : null); - const [status, setStatus] = useState(() => - isHydrated ? setImageAndGetInitialStatus(props, imageRef) : "pending", - ); + const [status, setStatus] = useState("pending"); useEffect(() => { if (!imageRef.current) return; @@ -97,6 +96,12 @@ export function useImage(props: UseImageProps = {}) { } }; + useSafeLayoutEffect(() => { + if (isHydrated) { + setStatus(setImageAndGetInitialStatus(props, imageRef)); + } + }, [isHydrated]); + /** * If user opts out of the fallback/placeholder * logic, let's just return 'loaded'