[React] 주니어 개발자의 커스텀 훅 NPM 배포 후기
취미로 하는 개발

[React] 주니어 개발자의 커스텀 훅 NPM 배포 후기

 

ryan-custom-hooks

react custom hook made by Ryan

www.npmjs.com

 

GitHub - Jonghakseo/ryan-custom-hooks: ryan's custom hook

ryan's custom hook. Contribute to Jonghakseo/ryan-custom-hooks development by creating an account on GitHub.

github.com

 

축) 커스텀 훅 드디어 배포

 

자주 사용하는 나만의 커스텀 훅을 만들어서 배포하고 싶은 생각이 있었는데,

문서화 작업이나 컴파일 작업 등의 환경을 만들기 귀찮다는 핑계로 미루고 있었다.

 

그러다가 이러한 귀찮은 작업들을 다 해놓은 템플릿을 깃헙에서 발견하고 바로 만들게 되었다.

 

 

GitHub - colbyfayock/use-custom-hook: ⚛️ A starter template for creating a new React Hook

⚛️ A starter template for creating a new React Hook - GitHub - colbyfayock/use-custom-hook: ⚛️ A starter template for creating a new React Hook

github.com

 

날로 먹을 수 있는 기회...?

colbyfayock 고마워요...!


첫 배포는 가볍게 3가지 훅으로 시작했다. 기능들은 굉장히 간단하고 별거 없다.

내가 자주 사용하는 녀석들을 앞으로도 추가해서 쓸 계획이다.

 

좀 더 다양한 훅을 넣어보고 싶었는데 프로젝트에서 사용 중인 훅들이 비즈니스 로직이 얽혀있거나 2개 이상의 복합적이고 의존적인 훅의 조합이 많아 일단은 의존성이 없고 간단한 훅 위주로 세팅했다.

 

간단히 소개해보자면,

 

useToggle 

boolean 값을 빠르게 토글 하는 데 사용하는 훅.

보통 나는 모달 등의 열림 닫힘 상태를 관리할 때 사용했다. toggle 메서드 하나로 두 개의 액션을 간편하게 할 수 있어서 간결하게 쓰기 좋다.

세 번째 인자는 setState 역할을 하긴 하는데, 보통은 안 꺼내 쓰고 [isShow, toggle] 이렇게 두 개만 빼서 쓴다.

const [isShow, toggleModal, setShowModal] = useToggle()
// toggleModal == setShowModal((prev) => !prev);

<button onClick={toggleModal}/>
<Modal visible={isShow} onClose={toggleModal}/>
 

useToggleExample - CodeSandbox

useToggleExample by unqocn using react, react-dom, react-scripts, ryan-custom-hooks

codesandbox.io

useMountFocus

마운트 후 특정 DOM element를 focus 한다.

렌더링 로직 바깥으로 보내기 위해 setTimeout으로 한 번 랩핑 한 focus 함수를 실행한다.

보통 input 포커스 혹은 모달 마운트시 닫기 버튼 자동 포커스 등에 사용한다.

useMountFocus(btnRef)

<button ref={btnRef} />
 

useMountFocusExample - CodeSandbox

useMountFocusExample by unqocn using react, react-dom, react-scripts, ryan-custom-hooks

codesandbox.io

useFocusBlur

특정 DOM element의 focus와 blur 상태를 추적한다.

onFocus / onBlur / state를 구현하는 수고를 덜었다... 정도의 의미가 있겠다.

const onFocus = useFocusBlur("target_div")

<div id="target_div">{onFocus}</div>
 

useFocusBlurExample - CodeSandbox

useFocusBlurExample by unqocn using react, react-dom, react-scripts, ryan-custom-hooks

codesandbox.io

 

 

별거 아닌 훅들이지만 막상 배포하고나니 기분이 뿌듯하다.

앞으로 유용한 훅들이나 자주 쓰는 컴포넌트들을 묶어서 배포해야겠다.

 

나라도 열심히 쓰자!