useSetTimeout

Taek·2020년 6월 14일
0
import { useEffect, useRef } from 'react';

function useSetTimeout(timeoutCallback, seconds) {
    const timeoutId = useRef();

    useEffect(() => {
        timeoutId.current = setTimeout(timeoutCallback, seconds);
        return () => clearTimeout(timeoutId.current);
    }, [])
}

export default useSetTimeout;

component가 unmount 된 이후 상태가 변경되면 메모리 누수가 발생 할 수 있다. 따라서 setTimeout 이나 setInterval 같은 비동기 작업을 할 때 유의해야 한다.

경고 메세지를 수도 없이 보다 useRef를 활용한 커스텀 훅을 만들었다.
매개변수 timeoutCallback 에는 setState 함수를 인자로 받는다.

// example
const NotFound = () => {
    const [wait, setWait] = useState(true);

    const timeoutCallback = () => setWait(false);
    useSetTimeout(timeoutCallback, 4000);

    return (
        <div>
      	    {wait ? <p>존재하지 않는 페이지 입니다. 메인 페이지로 이동 합니다.</p> : <Redirect to='/' />}
        </div>
    );
}

0개의 댓글