1

I'm using Functional components in my react app. I need to delay the content under the return() of my react component by 3 seconds. Here is the way I'm looking for it. Please help me to do it in this way.

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

const Example = () => {
    useEffect(() => {

        //some codes

    }, []);

    //some codes

    return (
        <div>
            {/* Return Something */}
        </div>
    );
};

export default Example;
3
  • Do you want to delay until value of data is updated? Commented Nov 5, 2020 at 12:45
  • What do you mean by delay? Commented Nov 5, 2020 at 12:46
  • @Prime i need to delay 3 seconds Commented Nov 5, 2020 at 13:09

2 Answers 2

3
import React, { useEffect, useState } from 'react';

const Example = () => {
    const [loading, setLoading] = useState(true);
    useEffect(() => {

      setTimeout(() => {
         setLoading(false)
      }, 3000)

    }, []);

    //some codes

    if(!loading){
       return <div>loading...</div> 
    }

    return (
        <div>
            {/* Return Something */}
        </div>
    );
};

export default Example;
Sign up to request clarification or add additional context in comments.

2 Comments

i'm sorry i need to delay by 3 seconds
@ NavinduKavishka you can return null instead of loading message. if(!loading){ return null }
2

use the setTimeout method calls a function or runs some code after a period of time, specified using the second argument.

const [state,setState] = useState({
 text:"",
});

useEffect(() => {
const timer = setTimeout(() => {
 setState({
  text:"Hello World"
 });
}, 3000);
return () => clearTimeout(timer);
}, []);

return (
<h1>{state.text}</h1>
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.