I wanted to render a ReactJS component for a limited amount of time every time (think of a notification that pops up and then goes away). Ideally, we would like to be able to apply this limited time rendering to any component, so this was an excellent candidate for a Higher Order Component (HOC).
ReactJS HOC for Limited Time Rendering
The wrapped component will render for the given number of seconds, whenever the props are updated.
import { useState, useEffect, useRef } from 'react';
/**
* Limit rendering of component to a given number of seconds (HOC).
*
* @param {Component} wrapped component to render.
* @param {number} Number of seconds to display before hiding.
* @return {Component} wrapped component with limited render time.
*/
const WithLimitedTimeRender = (
WrappedComponent,
delayUntilHideInSeconds,
) => function Comp(props) {
const [isVisible, setIsVisible] = useState(true);
const timeoutRef = useRef(null);
useEffect(() => {
// One of our props has changed, render WrappedComponent.
setIsVisible(true);
// Set a timeout for when to stop rendering the WrappedComponent.
timeoutRef.current = setTimeout(
() => {
setIsVisible(false);
},
delayUntilHideInSeconds * 1000
);
// Cleanup: before re-executing the useEffect (or on component unmount),
// clear the timeout.
return () => clearTimeout(timeoutRef.current);
}, [props]);
if (! isVisible) {
return null;
}
return <WrappedComponent {...props} />;
};
export default WithLimitedTimeRender;
How it is Used
The <Notification>
component is wrapped in the HOC WithLimitedTimeRender()
to create <NotificationWithLimitedTimeRender>
, which can be used in the same way as the <Notification>
component (except it will stop rendering after 2 seconds).
import Notification from './components/Notification.js';
import WithLimitedTimeRender from './hocs/WithLimitedTimeRender';
const NotificationWithLimitedTimeRender = WithLimitedTimeRender(
Notification,
2, // seconds
);
return (
<NotificationWithLimitedTimeRender
message={myValue}
/>
);
Example
I put together an example using Create React App which is available on GitHub (salcode/react-hoc-limited-display-time).
Leave a Reply