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/

 

Making setInterval Declarative with React Hooks

How I learned to stop worrying and love refs.

overreacted.io

 

번역 / 리액트 훅스 컴포넌트에서 setInterval 사용 시의 문제점

Dan abramov의 https://overreacted.io/making-setinterval-declarative-with-react-hooks/ 번역입니다.All copyrights to Dan Abramovtranslated by Jake seoTHE

velog.io

 

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]);
}