[React] 컴포넌트가 어떤 hooks를 썼는지 알 수 있을까 (feat. useDebugValue)

dev stefanCho·2022년 3월 6일
0

react

목록 보기
18/19
post-thumbnail

하나의 컴포넌트에는 custom hooks나 기본 react hooks 등 여러개의 hooks를 사용합니다.
1개,2개가 모여 5개,6개가 되버리면 컴포넌트내에서 어떤 hooks를 사용하고 있는 지 어떤상태인지 헷갈리기 쉽상입니다.

hooks에 label 붙이기

이런경우, hooks내에 label을 붙이는 방법이 있습니다.
바로 useDebugValue를 사용하는 것입니다.

코드 예시

아래 코드를 봅시다.
다른 것 다 무시하고, useMyCustomHook에 있는 useDebugValue를 보세요.
hooks내에 있는 useDebugValue가 이 hooks를 대표하는 label이 될 것입니다.

import { useContext, useDebugValue, useState } from 'react';
import { ItemContext } from '../App';
import { Item } from './Item';
import './ItemList.css';

function useMyCustomHook() {
  const [isOnline, setIsOnline] = useState<boolean>(true);
  useDebugValue(isOnline ? 'is online-(debug)' : ' is offline-(debug)');
  return isOnline;
}

export const ItemList: React.FC = () => {
  const value = useContext(ItemContext);
  const isOnline = useMyCustomHook();

  if (typeof value === 'string') return null;

  return (
    <div className=''>
      <div className='item-list'>Item 리스트</div>
      {value.items.map((a) => {
        return <Item key={a.name} item={a} />;
      })}
    </div>
  );
};

리액트 개발자도구에서 확인하기

이미지를 보면 ItemList에 MyCustomHook이란게 있습니다.
ItemList 컴포넌트에서 useMyCustomHook을 사용했다는 것을 알 수 있는 것입니다.
(원래 full name은 useMyCustomHook이지만, 맨 앞에 use는 자동으로 빠진상태로 label이 생성됩니다.)

주의사항

useDebugValue는 반드시 hooks내에서 사용해야 동작합니다.
component의 top level에서 사용하면 아무기능도 하지 않습니다.
stackoveflow를 참고해봅시다.

마치며

We don’t recommend adding debug values to every custom Hook. It’s most valuable for custom Hooks that are part of shared libraries.

Docs에서는 useDebugValue를 모든 hooks에 붙일 필요는 없다고 합니다.
제 생각에는 자주 사용하는 hooks에다가 하나 붙여두면, 디버깅할 때 좋을 것 같습니다. 끝.

profile
Front-end Developer

0개의 댓글