Type something to search...
React Hooks 완벽 가이드

React Hooks 완벽 가이드

React Hooks란?

React Hooks는 함수형 컴포넌트에서 상태와 라이프사이클 기능을 “갈고리처럼” 끌어올려 사용할 수 있게 해주는 기능입니다.

가장 중요한 Hooks

useState - 상태 관리

함수형 컴포넌트에서 상태를 관리하는 가장 기본적인 Hook입니다.

import { useState } from 'react';

export function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>클릭 횟수: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        증가
      </button>
    </div>
  );
}

useEffect - 부수 효과 처리

컴포넌트가 마운트, 업데이트, 언마운트될 때 특정 작업을 수행합니다.

import { useEffect, useState } from 'react';

export function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // 컴포넌트 마운트 시 실행
    fetch('/api/data')
      .then(res => res.json())
      .then(data => setData(data));

    // 정리 함수 (언마운트 시 실행)
    return () => {
      console.log('정리 작업');
    };
  }, []); // 의존성 배열

  return <div>{data && <p>{data.title}</p>}</div>;
}

useContext - 전역 상태 관리

Props Drilling을 피하고 전역 상태를 공유합니다.

import { createContext, useContext } from 'react';

const ThemeContext = createContext();

export function useTheme() {
  return useContext(ThemeContext);
}

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

Hook 규칙

⚠️ 반드시 지켜야 할 규칙들:

  1. Top Level에서만 호출 - 반복문, 조건문 내에서 사용 금지
  2. React 함수에서만 - 일반 JavaScript 함수에서 사용 불가
  3. 순서 유지 - Hook의 호출 순서가 항상 같아야 함

커스텀 Hook 만들기

반복되는 로직을 커스텀 Hook으로 추출하세요.

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.log(error);
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      setStoredValue(value);
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

더 배우기

React Hooks를 마스터하면 더욱 강력하고 재사용 가능한 컴포넌트를 만들 수 있습니다!

Related Posts