I have an image that I take from an API endpoint. For a reason, I’m importing the image component inside a Suspense
with a fallback. The problem is that every time a useState
or a useEffect
is executed, the fallback of the Suspense
is shown. Is there any way to prevent the Suspense
fallback from being shown after the first render or when the image is cached?
export async function AvatarIcon({ id }: { id: string }) {
const avatarIcon = await getAvatarIcon(id)
return (
<div className="">
<Image
src={`data:image/png;base64, ${avatarIcon}`}
height={40}
width={40}
className="relative z-0 h-full w-16"
alt="Avatar Icon"
></Image>
</div>
)
}
The other component where I use Suspense
:
<div>
<Suspense fallback={<div></div>}>
<AvatarIcon id={user.id} />
</Suspense>
</div>
2
Answers
)
fallback
is running because the default value ofloading
prop is "lazy". from docsif you change the
loading="eager"
, this might work (I di not test it out) because the component is already loaded and ready to render. The Suspense component only shows its fallback content when the wrapped component is not ready to be renderedBut I think that setting an "eager" option inside Suspense doesn’t make sense because
Suspense
is specifically designed to handle components that load asynchronously.since you are fetching the image, maybe you should be caching this fetch with
useSwr
or with unstable_cachesince you get the image from api, next.js has loader file option. for example, for cloudinary
// Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg
export default function cloudinaryLoader({ src, width, quality }) {
const params = [‘f_auto’, ‘c_limit’,
w_${width}
,q_${quality || 'auto'}
]return
https://example.com/${params.join(',')}${src}
}
in this loader file, you can confire Caching Behavior :