shubham agrawal
shubham agrawal

Reputation: 3541

How to add delay in React.js?

I am new to React.js. I am not sure how to add delay to render in React.js. What is the best way to add delay.

I am adding the following code in render but its not working.

setTimeout(function() {
   
}, 1000);

Upvotes: 70

Views: 260147

Answers (6)

user24758431
user24758431

Reputation:

This is the simple function component which illustrate

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

function TimeoutTest() {
  const [showContent, setShowContent] = useState(false);

  useEffect(() => {
    const delay = setTimeout(() => {
      setShowContent(true);
    }, 2000);

    return () => clearTimeout(delay);
  }, []);

  return (
    <div>
      {showContent && (
        <div>
          {/* Your content goes here */}
        </div>
      )}
    </div>
  );
}

export default TimeoutTest;

Upvotes: 0

Alan
Alan

Reputation: 10145

With React hooks. It will wait 5s and then render this component.

import React from 'react'

const DeleayComponent = () => {
  const [show, setShow] = React.useState(false)

  React.useEffect(() => {
    const timeout = setTimeout(() => {
      setShow(true)
    }, 5000)

    return () => clearTimeout(timeout)

  }, [show])

  if (!show) return null

  return <>OK, Render</>
}

export default DeleayComponent

Upvotes: 27

Ronit Roy
Ronit Roy

Reputation: 960

Pure typescript Solution

You would be able to create delay function with async:

function timeout(delay: number) {
    return new Promise( res => setTimeout(res, delay) );
}

And then call the function:

await timeout(1000); //for 1 sec delay

Upvotes: 57

Rob van Dijk
Rob van Dijk

Reputation: 722

Not sure why you would want to do this, but something like this?

The component's constructor:

constructor(props) {
    super(props);
    this.state = {
        render: false //Set render state to false
    }
}

On component mount:

componentDidMount() {
  setTimeout(function() { //Start the timer
      this.setState({render: true}) //After 1 second, set render to true
  }.bind(this), 1000)
}

The render method:

render() {
    let renderContainer = false //By default don't render anything
    if(this.state.render) { //If this.state.render == true, which is set to true by the timer.
        renderContainer = <div>Look at me! I'm content!</div> //Add dom elements
    }
    return (
      renderContainer //Render the dom elements, or, when this.state == false, nothing.
    )
  }

So when the timer fires, render is set to true. Because render is stored in state, this also triggers a re-render of the component. The if statement simply instructs renderContainer to not display anything unless the state render is true. You could also show a text indicating the component is loading, by instead of declaring renderContainer= false at the top, declaring the default as renderContainer=<div>Component is loading..</div> for example.

Upvotes: 36

Mehdi Faraji
Mehdi Faraji

Reputation: 3816

The easiest way to display a component after a time is conditional rendering like this :

constructor(props) {
    super(props);
    this.state = {
        render: false 
    }
}
handleRender = () => {
  setTimeout(() => {
     this.setState({ render : !this.state.render })
  }, 1000);
}

render () {
   return (
          <div>
             <button onClick={handleRender}>Set render to true</button>
             { this.state.render ? <Component /> : null }
          </div>
   )
}

When you click the button after one second it will set the render state to true and the <Component /> will show up .

If you want to run setTimeout on component load and not clicking the button you can have it in componentDidMount lifecycle like this :

componentDidMount(){
  setTimeout(() => {
     this.setState({ render : !this.state.render })
  }, 1000);
}

Hope you fully understood how you can achieve this way of rendering components .

Upvotes: 4

msanjay
msanjay

Reputation: 2343

One way to use hook with setTimeout is to set a property after the interval.

import { useState, useEffect } from "react";

const BotResponse = () => {

......

const [botMessage, setBotMessage] = useState('');

// function called from some user interaction
const botResponse = (msg) => {
   setTimeout(function() {
      setBotMessage(msg);
   }, 500);
};

useEffect(() => {
    console.log("bot msg... " + botMessage);

    // display the bot message

}, [botMessage]); // listening to a change on this property
}

Upvotes: 0

Related Questions