It is easy to implement the countdown method using hooks, the key is how to optimize it

The first way

Use two useState, useEffect

The second way

Use a useState

import React, { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(5);
  useEffect(() = > {
    const newTimer = setInterval(() = > {
      if (count > 0) {
        setCount((c) = > c - 1); }},1000);
    return () = > clearInterval(newTimer);
  }, [count]);

  return <div>{count}</div>;
}

Copy the code

The third way

Because the data is updated every second and setInterval is created every second it’s better to use setTimeout

import React, { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(5);
  useEffect(() = > {
    const newTimer = setTimeout(() = > {
      if (count > 0) {
        setCount((c) = > c - 1); }},1000);
    return () = > clearInterval(newTimer);
  }, [count]);

  return <div>{count}</div>;
}
Copy the code

The fourth way

If you still want to use setInterval, you need to ensure that useEffect is executed only once, so you need to pass in an empty array for the second parameter. However, passing in an empty array will cause a warning because it uses a variable defined by useState without dependencies, and the count may be old every time. The solution is not to use count in useEffect

import React, { useState, useEffect } from "react";
export default function App() {
    const [count, setCount] = useState(5);
    useEffect(() = > {
        const newTimer = setInterval(() = > {
            setCount((c) = > {
                if(c ! = =0) {
                    return c - 1;
                }
                clearInterval(newTimer);
                return 0;
             });
    }, 1000); } []);return <div>{count}</div>;

}

Copy the code