Skip to content
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

feat(react): useCombinedRefs, useScrollEvent 훅 추가 #44

Merged
merged 3 commits into from
Aug 22, 2021
Merged
Show file tree
Hide file tree
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
29 changes: 29 additions & 0 deletions packages/react/src/hooks/useCombinedRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Ref, useCallback, MutableRefObject, RefCallback } from 'react';

/**
* 여러 개의 ref를 합칠 수 있는 훅입니다.
* @example
* const Foo = forwardRef((props, fowardedRef) => {
* const ref = useRef();
* const combinedRef = useCombinedRefs(fowardedRef, ref);
*
* // div가 업데이트되면 ref, fowardedRef 둘 다 업데이트 됨
* return <div ref={combinedRef} />
* });
*/
export default function useCombinedRefs<T>(...refs: Array<Ref<T>>): RefCallback<T> {
const combinedRef = useCallback(
(value: T) => {
refs.forEach((ref) => {
zi-gae marked this conversation as resolved.
Show resolved Hide resolved
if (typeof ref === 'function') {
ref(value);
} else if (ref != null) {
(ref as MutableRefObject<T>).current = value;
}
});
},
[refs]
);

return combinedRef;
}
20 changes: 20 additions & 0 deletions packages/react/src/hooks/useScrollEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { RefObject, useEffect } from 'react';

/**
* 컴포넌트에 스크롤 이벤트를 추가하는 hook입니다.
* useEffect dependency로 hook의 인자인 ref, scrollCallback을 포함하고 있어
* ref, scrollCallback의 레퍼런스가 변경 될 때마다 스크롤 이벤트가 바인딩됩니다.
* 이 부분을 참고하셔서 성능이슈가 발생하지 않도록 잘 관리해주세요.
*/
const useScrollEvent = (ref: RefObject<HTMLElement>, scrollCallback: () => void) => {
useEffect(() => {
if (ref.current === null) {
return;
}

ref.current.addEventListener('scroll', scrollCallback, { passive: true });
return () => ref.current?.removeEventListener('scroll', scrollCallback);
}, [ref, scrollCallback]);
};

export default useScrollEvent;