Son Ha Nguyen
Son Ha Nguyen

Reputation: 45

react-countdown resets when rendered in ReactJs

I am creating a game which user can tap a button as much as they can in a range of time.

I have use react-countdown to create Timer. But when I tap to a button, timer is auto reset.

Here my code.

import React, { useState } from "react"
import Countdown from 'react-countdown';

function App() {

  const [name, setName] = useState("")
  const [isLogin, setIsLogin] = useState(false)
  const [counter, setCounter] = useState(0)

  const submitName = () => {
    setIsLogin(true)
  }

  const updateCounter = () => {
    console.log(counter)
    setCounter(counter + 1)
  }

  return (
    <div>
      {!isLogin ? (
        <div>
          <input
            style={{ width: 300, height: 30 }}
            placeholder="Input name here"
            value={name}
            onChange={e => setName(e.target.value)}
          />
          <button
            style={{ width: 50, height: 20, background: "red" }}
            onClick={() => submitName()}
          >Go</button>
        </div>
      ) : (
          <div
            style={{ width: "100vw", height: "100vh", background: "yellow" }}>
            <Countdown date={Date.now() + 100000} />
            <h1>{name}</h1>
            <h3>Click counter: {counter} </h3>
            <button
              style={{
                width: 100,
                height: 50,
                background: "red",
                border: "none",
                borderRadius: 25,
                color: "white",
                cursor: "pointer"
              }}
              onClick={() => updateCounter()}>Click here!</button>
          </div>
        )
      }
    </div>
  );
}

export default App;

The problem is when I tap the button, setCounter(counter + 1) is running and rerender the page. That made the Counter reset. I know why it have issue but I cannot fix it.

Upvotes: 3

Views: 1452

Answers (2)

Nazim Sheikh
Nazim Sheikh

Reputation: 11

import React from 'react';

const time = React.useMemo(() => {
    return Date.now() + 120 * 1000;
}, []);

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53874

You need to memoize the Countdown component:

const CountdownWrapper = () => <Countdown date={Date.now() + 100000} />;
const MemoCountdown = React.memo(CountdownWrapper);

// usage
<MemoCountdown/>

Beforehand, on every render Date.now() gets a new value which resets the timer.

Edit Countdown reset

Upvotes: 4

Related Questions