How to delay rendering of React components?

Sometimes, we want to delay rendering of React components.

In this article, we’ll look at how to delay rendering of React components.

How to delay rendering of React components?

To delay rendering of React components, we use the setTimeout function.

For instance, we write

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

const Delayed = ({ children, waitBeforeShow = 500 }) => {
  const [isShown, setIsShown] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsShown(true);
    }, waitBeforeShow);

    return () => clearTimeout(timer);
  }, [waitBeforeShow]);

  return isShown ? children : null;
};

export default Delayed;

to create the Delayed component.

It renders the children when isShown is true.

isShown is set to true in the setTimeout callback with setIsShown(true); after waitBeforeShow milliseconds, which is in the useEffect callback.

When waitBeforeShow is changed, the useEffect callback is called.

clearTimeout is called right before waitBeforeShow is changed.

Then we use it by writing

export const LoadingScreen = () => {
  return (
    <Delayed>
      <div />
    </Delayed>
  );
};

Conclusion

To delay rendering of React components, we use the setTimeout function.