forEach with delay react code example

Example: how to display text one after one from an array with 2 seconds delay in react

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const messages = ["fetching from sources...", "loading account..."];

const Loader = props => {
  const { messages } = props;
  // Default to the first message passed
  const [messageIndex, setMessageIndex] = React.useState(0);

  React.useEffect(() => {
    // Move on to the next message every `n` milliseconds
    let timeout;
    if (messageIndex < messages.length - 1) {
      timeout = setTimeout(() => setMessageIndex(messageIndex + 1), 1000);
    }

    return () => {
      clearTimeout(timeout);
    };
  }, [messages, messageIndex]);

  return <div>{messages[messageIndex]}</div>;
};

function App() {
  return (
    <div className="App">
      <Loader messages={messages} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);