🌐 Web Development

Hooks

React Hooks

React Hooks are an innovative feature introduced in React 16.8 that lets function components use state management and lifecycle features. With useState, useEffect, useContext, and more, you can build complete React applications without class components.

πŸ“– Detailed Explanation

React Hooks is a feature officially released in React 16.8 in 2019 that allows function components to use state and lifecycle features. Before Hooks, using these features required writing class components. With the introduction of Hooks, it became possible to develop fully featured React applications using only function components.

The basic Hooks include useState (state management), useEffect (side effect handling), and useContext (context usage). useState adds a state variable to a component, and useEffect handles side effects such as data fetching, subscriptions, and DOM manipulation. useContext allows data to be shared across the entire component tree without prop drilling.

Additional Hooks include useReducer (complex state logic), useCallback (function memoization), useMemo (value memoization), useRef (mutable ref object), useLayoutEffect (synchronous DOM updates), and useImperativeHandle (ref customization). React 18 added new Hooks such as useId, useTransition, and useDeferredValue, which support concurrency features.

A custom hook (Custom Hook) is a function that starts with use and lets you extract logic to be reused across multiple components. By creating custom hooks such as useForm, useFetch, and useLocalStorage, you can reduce code duplication and separate concerns. Following the Rules of Hooks (call only at the top level, call only within React functions) ensures predictable and consistent behavior.

πŸ’» Code Example

import { useState, useEffect, useCallback, useMemo } from 'react';

// μ»€μŠ€ν…€ ν›…: 데이터 페칭
function useFetch<T>(url: string) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    const abortController = new AbortController();

    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url, {
          signal: abortController.signal
        });
        if (!response.ok) throw new Error('Network response was not ok');
        const result = await response.json();
        setData(result);
      } catch (err) {
        if (err.name !== 'AbortError') {
          setError(err as Error);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();

    // 클린업: μ»΄ν¬λ„ŒνŠΈ μ–Έλ§ˆμš΄νŠΈ μ‹œ μš”μ²­ μ·¨μ†Œ
    return () => abortController.abort();
  }, [url]);

  return { data, loading, error };
}

// μ»€μŠ€ν…€ ν›…: 둜컬 μŠ€ν† λ¦¬μ§€
function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch {
      return initialValue;
    }
  });

  const setValue = useCallback((value: T | ((val: T) => T)) => {
    setStoredValue(prev => {
      const valueToStore = value instanceof Function ? value(prev) : value;
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
      return valueToStore;
    });
  }, [key]);

  return [storedValue, setValue] as const;
}

// 메인 μ»΄ν¬λ„ŒνŠΈ
function UserDashboard() {
  const [searchTerm, setSearchTerm] = useState('');
  const [theme, setTheme] = useLocalStorage('theme', 'dark');
  const { data: users, loading, error } = useFetch<User[]>('/api/users');

  // 검색 κ²°κ³Ό λ©”λͺ¨μ΄μ œμ΄μ…˜
  const filteredUsers = useMemo(() => {
    if (!users) return [];
    return users.filter(user =>
      user.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [users, searchTerm]);

  // 이벀트 ν•Έλ“€λŸ¬ λ©”λͺ¨μ΄μ œμ΄μ…˜
  const handleSearch = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(e.target.value);
  }, []);

  const toggleTheme = useCallback(() => {
    setTheme(prev => prev === 'dark' ? 'light' : 'dark');
  }, [setTheme]);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div data-theme={theme}>
      <button onClick={toggleTheme}>Toggle Theme</button>
      <input
        type="text"
        value={searchTerm}
        onChange={handleSearch}
        placeholder="Search users..."
      />
      <ul>
        {filteredUsers.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

πŸ—£οΈ Examples of Practical Conversations

πŸ’¬ Situation: A situation where you are asked about your experience using Hooks in a technical interview

Interviewer "When should you use a cleanup function in useEffect? Do you have an example from an actual project?"
Candidate "A cleanup function is used for unsubscribing, clearing timers, canceling API requests, and so on. In a recent project, I worked with a WebSocket connection and had an experience where a memory leak occurred because the connection was not closed when the component unmounted. I resolved it by calling socket.disconnect() in the cleanup, and since then I have always applied fetch cancellation using AbortController as well."
Interviewer "Please explain the difference between useCallback and useMemo, and when you should use them."
Candidate "useCallback memoizes a function, while useMemo memoizes a computed value. useCallback is useful for preventing callback functions passed as props to child components from being recreated unnecessarily. useMemo is used to cache the result of an expensive calculation. However, applying them everywhere can actually make performance worse, so I profile with React DevTools and apply them only where there is an actual bottleneck."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More