import React, { useState, useRef, useCallback } from "react";
// null means pause
// 1000 means 1 sec
type DelayType = null | 1000;
// 🔴 Finish this function
function useIncreasingCount() {
const [count, setCount] = useState<number>(0);
const [delay, setDelay] = React.useState<DelayType>(null);
const delayRef = useRef<number>(null);
const toggleDelay = useCallback(() => {
clearInterval(delayRef.current);
if (delay) {
setDelay(null);
} else {
setDelay(1000);
delayRef.current = setInterval(() => {
setCount((count: number) => count + 1);
}, 1000);
}
}, [delay]);
return {
count,
delay,
toggleDelay,
};
}
export default function Counter() {
// 🔴 Finish this function
const { count, delay, toggleDelay } = useIncreasingCount();
return (
<div>
<h1>count: {count}</h1>
<button onClick={toggleDelay}>{delay ? "pause" : "play"}</button>
</div>
);
}