Search code examples
reactjstimercontrolled-component

Is using keys in React to recreate a component a bad practice?


Here is the scenario: I have a timer which counts from 60 to 0, when it's finished (it's on 0), user can select a button (which is located in the parent component) to restart the counter. Right now Timer has an onFinish prop, which executes once the timer is done, in it I increment key prop to recreate the Timer component. like this:

import React from 'react';

let counter = 0;
const timerDuration = 59;


const SMSConfirmation: React.FC = () => {


    const [timerFinished, setTimerFinished] = useState<boolean>(false)   

    const onTimerFinish = () => {
        setTimerFinished(true);
    }

    const restart = () => {
        setTimerFinished(false);
        counter++;
    }

    const handleButtonClick = () => {
        if (timerFinished) restart();
    }

    return (
        <div>

            <Timer key={counter}
            duration={timerDuration}  
            onFinish={onTimerFinish} />

            <Button onClick={handleButtonClick} />
        </div>
    )
}

export default SMSConfirmation;

The other approach is to make Timer component controlled and have an onChange prop. Considering that I just need to know when timer has finished and don't need the exact value every second, I used the first approach but it seems a little bit like a bad practice since I have rarely seen this approach.

What's your opinion?


Solution

  • A better approach in my view would be to store the timer state every tick and update state bound to the timer this way you don't recreate anything you just reset the state and start it over again