유튜브 영상 controller는 약 3초 동안 사용자의 움직임이 없으면 영상 controller를 숨김.

이를 react hook으로 간단히 만들어 봄

 

import { useEffect, useRef, useState } from 'react';

export default function useVideoControllers(playing: boolean) {
  const [showControllers, setShowControllers] = useState(true);

  const timeout = useRef<number | null>();

  useEffect(() => {
    const showControllers = () => {
      setShowControllers(true);
      if (timeout.current) window.clearTimeout(timeout.current);
      timeout.current = window.setTimeout(() => {
        setShowControllers(false);
      }, 3500);
    };
    window.addEventListener('mousemove', showControllers);
    return () => window.removeEventListener('mousemove', showControllers);
  }, []);

  return { showControllers };
}

 

알게된 것

  • state가 바뀌면 그냥 local 변수는 값의 재할당이 일어난다
    • re-render와 상관없이 data를 유지하고 싶으면 ref를 꼭 쓰자!!! useRef 쓸 일이 생각보다 정말 많네
  • 등록한 setTimeout은 clearTimeout으로 없앨 수 있다
  • setTimeout의 return 값은 number 형식의 id 이다

+ Recent posts