React hooks countdown example


Posted 2 months ago by Ryan Dhungel

Category: React Hooks

Viewed 277 times

Estimated read time: 1 minute

In the following example, you can see how I am able to redirect user after the countdown that start at 5. Each second setInterval function runs while updating the state with setRun function. setRun is important to controll the behaviour of useEffect. run is a dependency of useEffect. You should be able to take the code and modify to suit your need.

 

import { useState, useEffect } from 'react';
import Layout from '../../components/Layout';
import withUser from '../withUser';
import { signout } from '../../helpers/auth';

const User = ({ user }) => {
    const [second, setSecond] = useState(5);
    const [run, setRun] = useState(false);

    useEffect(() => {
        const myInterval = setInterval(() => {
            setSecond(second - 1);
            setRun(!run);
        }, 1000);
        second === 0 && signout();
    }, [user === null && run]);

    return (
        <Layout>
            <p>user - private page for logged in user only</p>
            {user === null && (
                <div className="alert alert-danger">
                    You token has expired. Loggging you out in {second} second.
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            )}
        </Layout>
    );
};

export default withUser(User);