React

useUnmountEffect

TypeScript
TypeScript
React
React
컴포넌트가 언마운트될 때 클린업 로직을 호출하는 훅입니다. 클린업 로직을 명시적으로 분리하고 싶을 때 사용합니다.

구현

import { useEffect } from 'react';

export function useUnmountEffect(callback: () => void): void {
  useEffect(() => {
    return () => callback();
  }, []);
}

사용법

1. 인터벌 정리

function Timer() {
  const intervalRef = useRef<ReturnType<typeof setInterval>>();

  const start = () => {
    intervalRef.current = setInterval(() => { ... }, 1000);
  };

  useUnmountEffect(() => {
    clearInterval(intervalRef.current);
  });

  return <button onClick={start}>시작</button>;
}