React, Next, Redux/🚀 React with Hooks
custom hook (2) : setInterval wrapping하기
DarrenKwonDev
2021. 1. 21. 03:03
이건 제가 굳이 설명하기보다 좋은 글이 있으니 이를 첨부하도록하겠습니다.
overreacted.io/making-setinterval-declarative-with-react-hooks/
import React, { useState, useEffect, useRef } from 'react';
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}