CodexBloom - Programming Q&A Platform

Next.js Image Component Causing FOUC on Dynamic Image Loading with Custom URLs

👀 Views: 28 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
next.js image performance javascript

I'm migrating some code and I'm experiencing a Flash of Unstyled Content (FOUC) scenario when using the Next.js Image component to load images dynamically from an external API... My application fetches image URLs from an API endpoint and then uses these URLs in the Image component. The images seem to load fine, but they appear briefly unstyled before being rendered correctly. I'm using Next.js version 12.2.0 and the `next/image` component with the default loader. Here's a simplified version of my code: ```javascript import Image from 'next/image'; import { useEffect, useState } from 'react'; const DynamicImageLoader = () => { const [imageUrl, setImageUrl] = useState(''); useEffect(() => { const fetchImage = async () => { const response = await fetch('https://api.example.com/images/1'); const data = await response.json(); setImageUrl(data.url); }; fetchImage(); }, []); return imageUrl ? ( <Image src={imageUrl} alt='Dynamic Image' width={500} height={300} /> ) : ( <p>Loading...</p> ); }; export default DynamicImageLoader; ``` The scenario occurs because there seems to be a delay in the image loading, resulting in a brief flash of the loading state or unstyled component before the image is displayed. I've tried adding a loading spinner and setting a fixed image size but that doesn't seem to help with the FOUC question. Also, I have ensured that the image URL is optimized and served over HTTPS to prevent mixed content issues. I've considered preloading the image, but I'm not sure how to implement that effectively with the dynamic aspect of the URL. Any suggestions on how to mitigate this FOUC scenario while maintaining the benefits of using the Image component would be greatly appreciated! I'm on Ubuntu 20.04 using the latest version of Javascript. Any ideas how to fix this? Is there a simpler solution I'm overlooking?