DEV Community

Pavan C
Pavan C

Posted on

12 2

Remove element from DOM in React way

We will be using useEffect Hook to execute JavaScript Window.setTimeout() function which will help hide an element in the DOM (a side effect).

From React docs,

Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

In the setTimeout function, set the state variable visible to false after some amount of delay, which comes from props. In this example, 5000 milliseconds. In other words, we are telling setTimeout function to set the visible variable to false after 5 seconds.

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

const Expire = props => {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setVisible(false);
    }, props.delay);
  }, [props.delay]);

  return visible ? <div>{props.children}</div> : <div />;
};

export default Expire;
Enter fullscreen mode Exit fullscreen mode

You might have thought what is the optional second argument, props.delay doing in the useEffect Hook. By doing that, we told React to skip applying an effect if certain values haven’t changed between re-renders. This is for performance optimization by skipping effects 💡.

Let's say you forgot you mention the second argument, you would notice that the app will cause unnecessary re-renders even after the element is hidden from DOM and thus affecting your app performance.

useEffect(() => {
  setTimeout(() => {
    setVisible(false);
  }, props.delay);
}); // This causes re-rendering effect
Enter fullscreen mode Exit fullscreen mode

Now that we are done with our functional component, let's bring it to action altogether 🚀. Pass in delay props (5000 milliseconds) to our Expire component and you will notice that the element would be hidden from the DOM after 5 seconds.

<Expire delay="5000">Hooks are awesome!</Expire>
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (1)

Collapse
 
chilupa profile image
Pavan C • Edited

Sure, If you are familiar with React class life cycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. They don't run in a loop.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up