Чтобы сбросить счетчик, позвоните setCount(0)
из resetInterval
:
Примечание: вы ошиблись onClick
на кнопке.
function Counter() {
const [count, setCount] = useState(0);
useInterval(() => {
// Your custom logic here
setCount(count => count + 1);
}, 1000);
const resetInterval = () => setCount(0);
return (
<>
<h1>{count}</h1>
<button onClick={resetInterval}>Reset</button>
</>
);
}
Комуостановить / возобновить интервал, который вы можете изменить рефакторингом useInterval
для возврата функции toggleRunning
и текущего состояния running
.
function useInterval(callback, delay) {
const savedCallback = useRef();
const intervalId = useRef(null);
const [currentDelay, setDelay] = useState(delay);
const toggleRunning = useCallback(
() => setDelay(currentDelay => (currentDelay === null ? delay : null)),
[delay]
);
const clear = useCallback(() => clearInterval(intervalId.current), []);
// Remember the latest function.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (intervalId.current) clear();
if (currentDelay !== null) {
intervalId.current = setInterval(tick, currentDelay);
}
return clear;
}, [currentDelay, clear]);
return [toggleRunning, !!currentDelay];
}
Пример работы с перезагрузкой и паузой / возобновлением ( Песочница *)1018 *)
const { useState, useEffect, useRef, useCallback, Fragment } = React;
function Counter() {
const [count, setCount] = useState(0);
const [toggle, running] = useInterval(() => {
// Your custom logic here
setCount(count => count + 1);
}, 100);
const resetCounter = () => setCount(0);
return (
<Fragment>
<h1>{count}</h1>
<button onClick={resetCounter}>Reset</button>
<button onClick={toggle}>{running ? "Pause" : "Resume"}</button>
</Fragment>
);
}
function useInterval(callback, delay) {
const savedCallback = useRef();
const intervalId = useRef(null);
const [currentDelay, setDelay] = useState(delay);
const toggleRunning = useCallback(
() => setDelay(currentDelay => (currentDelay === null ? delay : null)),
[delay]
);
const clear = useCallback(() => clearInterval(intervalId.current), []);
// Remember the latest function.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (intervalId.current) clear();
if (currentDelay !== null) {
intervalId.current = setInterval(tick, currentDelay);
}
return clear;
}, [currentDelay, clear]);
return [toggleRunning, !!currentDelay];
}
ReactDOM.render(<Counter />, root);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>