Skip to content

Feature/use unmount 추가 #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/hooks/useUnmountEffect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useEffect, useRef } from 'react';

/**
* 컴포넌트가 언마운트 될 때 전달받은 인자 함수를 호출하는 훅
*
* @param callback 언마운트 시에 호출될 함수
*/

type Fn = () => void;

const useUnmountEffect = (callback: Fn) => {
const callbackRef = useRef<null | Fn>(callback);

useEffect(() => {
// 최신 함수를 callbackRef에 저장
callbackRef.current = callback;
}, [callback]);

useEffect(() => {
return () => {
if (callbackRef.current) {
callbackRef.current();
}

callbackRef.current = null;
};
}, []);
};

export default useUnmountEffect;