I am new to Reactjs. I am not sure how to add delay
to render in Reactjs
.What is the best way to add delay.
I am adding the following code in render but its not working.
setTimeout(function() { }, 1000);
To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.
Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.
Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook's dependencies array and the function you pass to useEffect will run every time the state variables change.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With