Skip to content

Commit

Permalink
Merge pull request #51 from mbti-nf-team/feat/unmount-hook
Browse files Browse the repository at this point in the history
  • Loading branch information
saseungmin authored Oct 7, 2023
2 parents b8955b1 + 2f62d89 commit c16de8b
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/soft-radios-attend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nf-team/react": minor
---

feat(useUnmount): useUnmount hook 구현 및 적용
1 change: 1 addition & 0 deletions packages/react/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ export { default as useLessThenScrollY } from './useLessThenScrollY';
export { default as useResizeViewportHeight } from './useResizeViewportHeight';
export { default as useThrottleCallback } from './useThrottleCallback';
export { default as useTimeout } from './useTimeout';
export { default as useUnmount } from './useUnmount';
export { default as useUpdateEffect } from './useUpdateEffect';
23 changes: 23 additions & 0 deletions packages/react/src/hooks/useUnmount.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { act, renderHook } from '@testing-library/react';

import useUnmount from './useUnmount';

describe('useUnmount', () => {
const effectCallback = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
});

const useUnmountHook = () => renderHook(() => useUnmount(effectCallback));

it('unmount되면 콜백함수가 호출되어야만 한다', () => {
const { unmount } = useUnmountHook();

act(() => {
unmount();
});

expect(effectCallback).toHaveBeenCalledTimes(1);
});
});
14 changes: 14 additions & 0 deletions packages/react/src/hooks/useUnmount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useRef } from 'react';

import useEffectOnce from './useEffectOnce';

function useUnmount(fn: () => void) {
const fnRef = useRef(fn);

// NOTE - ref 각 렌더를 업데이트하여 변경하면 최신 콜백이 실행
fnRef.current = fn;

useEffectOnce(() => () => fnRef.current());
}

export default useUnmount;

0 comments on commit c16de8b

Please sign in to comment.