Remove element from DOM in React way

chilupa profile image Pavan Chilukuri ・2 min read

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(() => {
    }, 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(() => {
  }, 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

Posted on by:

chilupa profile

Pavan Chilukuri


Full Stack Developer πŸ’» Photographer πŸ“·


Editor guide

I barely learned hooks before I got off the train, so I have to map all of this to Vue to see what's what...

  <div><slot v-if="visible"></slot></div>

export default {
  props: ['delay'],
  data() {
    return { visible: true }
  mounted() {
    setTimeout(() => {
      this.visible = false;
    }, this.delay);
Enter fullscreen mode Exit fullscreen mode

The only thing I'm still wondering about is what you mentioned, "we told React to skip applying an effect", but useEffect is called once, setTimeout and its callback are called once...do effects run in a loop or something?


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.