Skip to content
Advertisement

How to render each function component UI (synchronous)

I have two UI function component and i wanna render them synchronous, I mean when the first component render finished,it will be delete into DOM then the second component will be render after that.

import React, {useEffect, useState} from "react";
import Home from "./Home";
import Loading from "./Loading";
export default function Web() {
  const [beforeLoad, setBeforeLoad] = useState(false);

  useEffect(() => {
    async () => {
      await (new Promise<void>(resolve => {
        setTimeout(() =>{
          resolve(() => setBeforeLoad(true))
        }, 2500)
      }))
  }}, [])
    if(!beforeLoad) {
      return <div className="bg-gradient-to-r from-violet-500 to-fuchsia-500" style={{
        width: '100wh',
        height: '100vh',
        padding: 0,
        margin: 0,
        overflow: 'hidden',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        perspective: '500px'
      }}>
        <Loading />
      </div>
    } else if(beforeLoad) {
      return <Home />
    }
}

i used async await into hook but maybe i’m wrong.

as you can see, i wanna render Loading component first then Home component will be render after that.

Advertisement

Answer

You don’t need to use async/await here, you can do it with JavaScript’s setTimeout function

import React, { useEffect, useState } from "react";

export default function Web() {
  const [beforeLoad, setBeforeLoad] = useState(false);

  useEffect(() => {
    setTimeout(() => setBeforeLoad(true), 2500);
  }, [beforeLoad]);
  if (!beforeLoad) {
    return (
      <div
        className="bg-gradient-to-r from-violet-500 to-fuchsia-500"
        style={{
          width: "100wh",
          height: "100vh",
          padding: 0,
          margin: 0,
          overflow: "hidden",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          perspective: "500px"
        }}
      >
        <h1>loading...</h1>
      </div>
    );
  } else if (beforeLoad) {
    return <h2>loading finished!</h2>;
  }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement