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;
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
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>
Top comments (1)
Sure, If you are familiar with React class life cycle methods, you can think of
useEffect
Hook ascomponentDidMount
,componentDidUpdate
, andcomponentWillUnmount
combined. They don't run in a loop.