Jeeeyoung Log
frontend#react#hooks

React Hooks 완전 정복

useState

상태를 관리하는 가장 기본적인 훅입니다.

const [count, setCount] = useState(0);

초기값으로 함수를 전달하면 최초 렌더링에서만 실행됩니다 (lazy initialization).

const [list, setList] = useState(() => heavyComputation());

useEffect

사이드 이펙트를 처리할 때 사용합니다. 렌더링 후 실행됩니다.

useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]); // count가 바뀔 때만 실행

클린업

타이머, 구독, 이벤트 리스너처럼 해제가 필요한 경우 클린업 함수를 반환합니다.

useEffect(() => {
  const timer = setInterval(() => setCount((c) => c + 1), 1000);
  return () => clearInterval(timer);
}, []);

useCallback

함수를 메모이제이션합니다. 자식 컴포넌트에 함수를 props로 전달할 때 불필요한 리렌더링을 막습니다.

const handleClick = useCallback(() => {
  setCount((c) => c + 1);
}, []); // 의존성이 없으면 최초 1회만 생성

useMemo

값을 메모이제이션합니다. 비용이 큰 연산 결과를 캐싱할 때 사용합니다.

const sorted = useMemo(() => {
  return [...items].sort((a, b) => a.name.localeCompare(b.name));
}, [items]);