How to use setTimeout to show a component only after a certain time with React?

Asked

Viewed 167 times

3

I want a certain component to appear on the screen after 1 second. You can do this using JSX block?

When I put the code below, a number appears on the screen instead of the message.

function App() {
  return (
    <>
      {setInterval(() => {
        return (
          <div className="answer">
            <input
              type="text"
              placeholder="Nome e sobrenome"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <button type="submit" onClick={handleInputName}>
              <PlayArrowIcon fontSize="large" color="primary" />
            </button>
          </div>
        );
      }, 1000)}
    </>
  );
}

1 answer

3


That won’t work because the setInterval does not behave properly to the model that React works with.

In JSX, everything put between keys ({}) is evaluated as an expression by React and rendered in the document. As setTimeout, in the browsers, always returns a number (the ID of the timeout), it is he who will be rendered. Thus, put the JSX code inside the setTimeout is wrong and of nothingness will help, since they are incompatible Apis for direct use.

To make it work the way the question example shows, setTimeout would have to at least fit React’s "Suspense" model.

As primitive of the web, the setInterval will never fit this model. They are different technologies that were not designed to work together without a handling additional.

It is about this "handling" that we will deal with next.


To make a component only render after a certain time, you must create a state variable to "know" when the component must be hidden or visible. You should also use the useEffect to "integrate" with the setTimeout.

A trivial example would be this:

function App() {
  // Inicializamos um booleano no estado do componente para sabermos quando
  // devemos mostrar ou esconder o componente de acordo com o `setTimeout`.
  const [finishedTimeout, setFinishedTimeout] = React.useState(false);

  // O "manejo" necessário: integraremos o `setTimeout` com o React através do
  // hook `useEffect`:
  React.useEffect(() => {
    const id = setTimeout(() => {
      setFinishedTimeout(true);
    }, 1000);

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

  return (
    <div>
      <h1>Sempre visível.</h1>
      {finishedTimeout && <h1>Visível apenas 1s depois.</h1>}
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('#root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

It is important to understand the functioning of React Hooks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.