Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional rendering with useEffect() and setTimeOut()

Tags:

reactjs

I've got two components in my react application. one of them is for the initial loading that will show some loading animations, and I want this one to render for about three seconds, and the other component is just a counter that I want to render after the first one. how can I do this with useEffect() and setTimeOut()? (or with any other methods)

function App() {
  return(
     <>
       <Loading />
       <Counter />
     </>
  )
}
like image 766
OmidJr Avatar asked Sep 06 '25 07:09

OmidJr


1 Answers

Here you go :

This is just a code snippet showing useEffect and setTimeout, in your case you can use real component instead of string in below.

Just run the snippet and hope it will clear your thoughts :

const { useState , useEffect } = React;

const App = () => {

  const [loading,setLoading] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    },3000);
  },[]);

  return (
    <div>
      { loading ? "Loading Component (will be gone in 3 secs)...." : "Counter Component"}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
like image 144
Vivek Doshi Avatar answered Sep 07 '25 19:09

Vivek Doshi