dfweb-v3 icon indicating copy to clipboard operation
dfweb-v3 copied to clipboard

FOUC?

Open w3bdesign opened this issue 2 years ago • 0 comments

there are other methods you can use to prevent FOUC in Next.js. One common approach is to set the opacity of the content to 0 before the page is loaded, and then fade it in once the JavaScript and CSS files are loaded. Here's an example of how to implement this:

Set the initial opacity of your content to 0 in your CSS:

.my-content {
  opacity: 0;
  transition: opacity 0.3s ease-in;
}

Use the useEffect hook to fade in the content once it's loaded:

import { useEffect, useState } from 'react';

function MyPage() {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    setIsLoaded(true);
  }, []);

  return (
    <div className={`my-content ${isLoaded ? 'opacity-100' : ''}`}>
      My page content
    </div>
  );
}

export default MyPage;

Here, we're using the useEffect hook to set the isLoaded state to true once the page is loaded. We're also using the opacity-100 class from Tailwind to fade in the content.

Add a loading state to your _app.js file: You can add a loading state to your _app.js file using the next/router module, which will be set to true when a page is navigating and false when it's done navigating:

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

function MyApp({ Component, pageProps }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const handleStart = (url) => setLoading(true);
    const handleComplete = (url) => setLoading(false);

    router.events.on('routeChangeStart', handleStart);
    router.events.on('routeChangeComplete', handleComplete);
    router.events.on('routeChangeError', handleComplete);

    return () => {
      router.events.off('routeChangeStart', handleStart);
      router.events.off('routeChangeComplete', handleComplete);
      router.events.off('routeChangeError', handleComplete);
    };
  }, []);

  return (
    <div className={`app ${loading ? 'cursor-wait' : ''}`}>
      <Component {...pageProps} />
    </div>
  );
}

export default MyApp;

Here, we're using the useRouter hook to get the router object, and adding event listeners to set the loading state to true when a page is navigating and false when it's done navigating. We're also using the cursor-wait class from Tailwind to change the cursor to a wait cursor while the page is loading.

By combining these techniques, you can prevent FOUC in Next.js and provide a smooth loading experience for your users.

w3bdesign avatar Mar 25 '23 06:03 w3bdesign