React - setTimeout

What is setTimeout?

The setTimeout method calls a function after a specific time. For example you would like to print a string after 2 seconds you can do something like this:

setTimeout(() => {
  console.log("my fancy text");
}, 2000);

What do we do here? In the setTimeout method we call a function without arguments. In this function we can do what we want. In this case we do a "console.log" and print some text. After our function we can specify the timeout time in milliseconds. In this case we wait 2000ms or 2s.

##vUsing setTimeout with React Hooks Using setTimeout in React is not that simple because rerendering or unmounting our component. But we can do this with some extra code and React hooks. If we unmount our component before the setTimeout is finished we get some errors and maybe some side effects that we dont want. So lets wrap it into a useEffect hook.

import React, { useEffect } from "react";

function App() {
  useEffect(() => {
    const timer = setTimeout(() => {
      console.log("my fancy text");
    }, 2000);
    return () => clearTimeout(timer);
  }, []);

  return <div>Nice app!</div>;

So what we do here with the useEffect hook? First we declare a variable and assign our setTimeout method to it. Nothing special but if we unmount our component we call a clearTimeout(timer) and we stop the setTimeout. This is a safe way to handle timeouts in React with hooks.

Using setTimeout with Component Lifecycle Methods

Above we see the "new" way of handling a setTimeout with hooks. But we can achieve this with the good old Component Lifecycles Methods:

import React from 'react'

class App extends React.Component {
  let timer = null

  componentDidMount() {
    timer = setTimeout(() => {
      console.log("my fancy text")
    }, 2000)

  componentWillUnmount() {

  render() {
    return (
      <div>Nice app!</div>