I have created a countdown timer component that passes the data to another component, and I use setTimeout
. The component works as expected but an warning appears in my console:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
As I use setTimeout
in useEffect
I tried to add clearInterval
in a return function, but this doesn't seem to help. Bellow you can find my component:
export default function createEvent(WrappedComponent) {
const Event = props => {
const [{ endDate }] = useState(props);
const [days, setDays] = useState('');
const [hours, setHours] = useState('');
const [minutes, setMinutes] = useState('');
const [seconds, setSeconds] = useState('');
const interval = useRef();
useEffect(() => {
interval.current = setInterval(() => {
const date = moment.unix(endDate).format('MM DD YYYY, h:mm a');
const then = moment(date, 'MM DD YYYY, h:mm a');
const now = moment();
const countdown = moment(then - now);
const daysFormat = countdown.format('D');
const hoursFormat = countdown.format('HH');
const minutesFormat = countdown.format('mm');
const secondsFormat = countdown.format('ss');
setDays(`${daysFormat} days`);
setHours(hoursFormat);
setMinutes(minutesFormat);
setSeconds(secondsFormat);
return () => {
clearInterval(interval.current);
interval.current = null;
};
}, 1000);
}, []);
return (
<WrappedComponent
days={days}
hours={hours}
minutes={minutes}
seconds={seconds}
{...props}
/>
);
};
return Event;
}
If I try to imitate clear from somewhere else place by adding another useEffect
right under the last one, like so:
useEffect(() => {
setTimeout(() => clearInterval(interval.current), 15000)
}, [])
Warning disappears but the countdown will not working any more. So how do I make this right, to not affect the countdown and clear the warning?