React Hooks 패턴 정리
실무에서 자주 사용하는 React Hooks 패턴과 커스텀 훅을 정리합니다.
개요
React Hooks는 함수형 컴포넌트에서 상태 관리와 사이드 이펙트를 처리할 수 있게 해주는 기능입니다. 이 글에서는 실무에서 유용한 패턴들을 정리합니다.
useDebounce
검색 입력 같은 상황에서 잦은 API 호출을 방지하기 위해 디바운스를 적용합니다.
import { useState, useEffect } from "react";
function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay);
return () => clearTimeout(handler); }, [value, delay]);
return debouncedValue;}
export default useDebounce;useIntersectionObserver
무한 스크롤이나 요소의 가시성을 감지할 때 유용합니다.
import { useEffect, useRef, useState } from "react";
function useIntersectionObserver(options = {}) { const ref = useRef(null); const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => { const observer = new IntersectionObserver(([entry]) => { setIntersecting(entry.isIntersecting); }, options);
if (ref.current) observer.observe(ref.current); return () => observer.disconnect(); }, []);
return [ref, isIntersecting];}useLocalStorage
브라우저 로컬 스토리지와 React 상태를 동기화합니다.
import { useState } from "react";
function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch { return initialValue; } });
const setValue = (value) => { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); };
return [storedValue, setValue];}정리
| Hook | 용도 | 핵심 |
|---|---|---|
useDebounce | 입력 디바운싱 | setTimeout + cleanup |
useIntersectionObserver | 가시성 감지 | IntersectionObserver API |
useLocalStorage | 로컬 상태 영속성 | localStorage + useState |
커스텀 훅을 잘 설계하면 컴포넌트의 로직을 깔끔하게 분리할 수 있습니다.