DEV Community

Pavan Chilukuri
Pavan Chilukuri

Posted on

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

Top comments (1)

Collapse
 
chilupa profile image
Pavan Chilukuri • 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.