Skip to content

Awesome example (thank you!) + some suggestionsΒ #1

@dwatts3624

Description

@dwatts3624

This was a super helpful example. Thank you! I was about to use a third-party component for this and your guide definitely gave me a solid foundation for this use case.

One commenter on the article noted this but I wanted to make a few suggestions to optimize performance. The code below has a few optimizations but the rest is just personal preference so use as you will:

import React, { useEffect, useMemo, useState } from 'react';
import isEmpty from 'lodash/isEmpty';

const calculateTimeLeft = (startDate) => {
    const difference = startDate - (new Date()).getTime();

    let timeLeft = {};

    if (difference > 0) {
        timeLeft = {
            days: Math.floor(difference / (1000 * 60 * 60 * 24)),
            hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
            minutes: Math.floor((difference / 1000 / 60) % 60),
            seconds: Math.floor((difference / 1000) % 60),
        };
    }

    return timeLeft;
};

function CountdownTimer({ startDate }) {
    
    const initialTimeLeft = useMemo(() => calculateTimeLeft(startDate), []);

    const [timeLeft, setTimeLeft] = useState(initialTimeLeft);

    useEffect(() => {
        const interval = setInterval(() => {
            const currentTimeLeft = calculateTimeLeft(startDate);

            if (isEmpty(currentTimeLeft)) {
                clearInterval(interval)
            }
            setTimeLeft(currentTimeLeft);
        }, 1000);

        return () => {
            clearInterval(interval)
        }
    }, []);


    const timerComponents = Object.keys(timeLeft).map((interval) => {
        if (!timeLeft[interval]) {
            return;
        }

        return (
            <span key={interval}>
                {timeLeft[interval]} {interval}{" "}
            </span>
        );
    });
    return (
        <div>
            {timerComponents.length ? timerComponents : <span>Time's up!</span>}
        </div>
    );
}

export default CountdownTimer;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions