How to show a loading indicator in Next.js page until the page is ready?

Here is the Next.js page code:

import { useEffect, useState } from 'react';

export default function Home() {
  // ##. variable to control display
  // ##. after data is fetched and ready
  const [dataReady, setDataReady] = useState(false);

  useEffect(()=>{
  // ##. This is to simulate an API data fetch call
    setTimeout(()=>{
      setDataReady(true)
    },3000);
  },[]);

  return (
    <>
      <h2>
        Page ready !!
      </h2>
      {
        dataReady &&
        <h3>
          Data is ready
        </h3>
      }
    </>
  )
}

If you run the above code, you can see that the page ready message show instantly the moment page is loaded. Data ready block appears only after the 3 seconds.

Now what we are trying to achieve here is to show loading until the data is ready.

Here is the solution:

import { useEffect, useState } from 'react';

export default function Home() {
  // ##. variable to control display
  // ##. after data is fetched and ready
  const [dataReady, setDataReady] = useState(false);

  useEffect(()=>{
  // ##. This is to simulate an API data fetch call
    setTimeout(()=>{
      setDataReady(true)
    },3000);
  },[]);

  // ## Loading will be show until data is ready
  if(!dataReady) return(<><p>Loading ..</p></>)

  return (
    <>
      <h2>
        Page ready !!
      </h2>
      {
        dataReady &&
        <h3>
          Data is ready
        </h3>
      }
    </>
  )
}