raw
Frontend

React Hooks 패턴 정리

2024.02.01·3분

개요

React Hooks는 함수형 컴포넌트에서 상태 관리와 사이드 이펙트를 처리할 수 있게 해주는 기능입니다. 이 글에서는 실무에서 유용한 패턴들을 정리합니다.

useDebounce

검색 입력 같은 상황에서 잦은 API 호출을 방지하기 위해 디바운스를 적용합니다.

javascript
1import { useState, useEffect } from "react";
2
3function useDebounce(value, delay) {
4 const [debouncedValue, setDebouncedValue] = useState(value);
5
6 useEffect(() => {
7 const handler = setTimeout(() => {
8 setDebouncedValue(value);
9 }, delay);
10
11 return () => clearTimeout(handler);
12 }, [value, delay]);
13
14 return debouncedValue;
15}
16
17export default useDebounce;
💡Tip

디바운스 딜레이는 일반적으로 300~500ms가 적절합니다. 타이핑 속도와 UX를 고려하여 조정하세요.

useIntersectionObserver

무한 스크롤이나 요소의 가시성을 감지할 때 유용합니다.

javascript
1import { useEffect, useRef, useState } from "react";
2
3function useIntersectionObserver(options = {}) {
4 const ref = useRef(null);
5 const [isIntersecting, setIntersecting] = useState(false);
6
7 useEffect(() => {
8 const observer = new IntersectionObserver(([entry]) => {
9 setIntersecting(entry.isIntersecting);
10 }, options);
11
12 if (ref.current) observer.observe(ref.current);
13 return () => observer.disconnect();
14 }, []);
15
16 return [ref, isIntersecting];
17}

useLocalStorage

브라우저 로컬 스토리지와 React 상태를 동기화합니다.

javascript
1import { useState } from "react";
2
3function useLocalStorage(key, initialValue) {
4 const [storedValue, setStoredValue] = useState(() => {
5 try {
6 const item = window.localStorage.getItem(key);
7 return item ? JSON.parse(item) : initialValue;
8 } catch {
9 return initialValue;
10 }
11 });
12
13 const setValue = (value) => {
14 const valueToStore = value instanceof Function
15 ? value(storedValue)
16 : value;
17 setStoredValue(valueToStore);
18 window.localStorage.setItem(key, JSON.stringify(valueToStore));
19 };
20
21 return [storedValue, setValue];
22}

정리

Hook용도핵심
useDebounce입력 디바운싱setTimeout + cleanup
useIntersectionObserver가시성 감지IntersectionObserver API
useLocalStorage로컬 상태 영속성localStorage + useState

커스텀 훅을 잘 설계하면 컴포넌트의 로직을 깔끔하게 분리할 수 있습니다.