🌐 Web Development

React

React.js

A UI library developed by Facebook. Component-based, with efficient rendering through the Virtual DOM. The most popular frontend tool.

πŸ“– Detailed Explanation

React is a JavaScript UI library released in 2013 by Facebook (now Meta), and it is currently one of the most widely used front-end tools. Under the philosophy of "Learn Once, Write Anywhere," it extends to the web (React), mobile (React Native), and even desktop (Electron + React). With the declarative programming approach, you only define the state of the UI, and React automatically handles DOM updates.

The core of React is Components and the Virtual DOM. Components split the UI into independent, reusable units, receive data through props, and manage internal state with state. The Virtual DOM is a virtual DOM tree in memory; when state changes, it is compared with the previous Virtual DOM (diffing), and only the minimum necessary real DOM updates are performed.

Hooks, introduced in React 16.8, are an innovative feature that lets function components use state management and lifecycle features. They include useState, useEffect, useContext, useReducer, useMemo, useCallback, useRef, and more. Since the introduction of Hooks, class components are rarely used, and function components have become the standard.

React 18 (2022) introduced Concurrent Rendering, Automatic Batching, Transitions, and Suspense for Data Fetching. React 19 (2024) added Server Components, Actions, and the use() hook, making full-stack React development possible. When used together with meta-frameworks such as Next.js and Remix, you can utilize various rendering strategies such as SSR, SSG, and ISR.

πŸ’» Code Example

React Hooks Basics
// React Hooksλ₯Ό ν™œμš©ν•œ ν•¨μˆ˜ν˜• μ»΄ν¬λ„ŒνŠΈ
import { useState, useEffect, useCallback, useMemo } from 'react';

interface User {
    id: number;
    name: string;
    email: string;
}

interface UserListProps {
    filterRole?: string;
}

export function UserList({ filterRole }: UserListProps) {
    // μƒνƒœ 관리
    const [users, setUsers] = useState<User[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [searchTerm, setSearchTerm] = useState('');

    // 데이터 페칭 - useEffect
    useEffect(() => {
        const controller = new AbortController();

        async function fetchUsers() {
            try {
                setLoading(true);
                const response = await fetch('/api/users', {
                    signal: controller.signal
                });

                if (!response.ok) throw new Error('Failed to fetch');

                const data = await response.json();
                setUsers(data);
            } catch (err) {
                if (err instanceof Error && err.name !== 'AbortError') {
                    setError(err.message);
                }
            } finally {
                setLoading(false);
            }
        }

        fetchUsers();

        // Cleanup function - μ»΄ν¬λ„ŒνŠΈ μ–Έλ§ˆμš΄νŠΈ μ‹œ μš”μ²­ μ·¨μ†Œ
        return () => controller.abort();
    }, [filterRole]); // filterRole이 λ³€κ²½λ˜λ©΄ λ‹€μ‹œ μ‹€ν–‰

    // λ©”λͺ¨μ΄μ œμ΄μ…˜ - useMemo (λΉ„μš©μ΄ 큰 계산)
    const filteredUsers = useMemo(() => {
        return users.filter(user =>
            user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            user.email.toLowerCase().includes(searchTerm.toLowerCase())
        );
    }, [users, searchTerm]);

    // 콜백 λ©”λͺ¨μ΄μ œμ΄μ…˜ - useCallback (μžμ‹μ—κ²Œ μ „λ‹¬ν•˜λŠ” ν•¨μˆ˜)
    const handleDelete = useCallback(async (userId: number) => {
        if (!confirm('정말 μ‚­μ œν•˜μ‹œκ² μŠ΅λ‹ˆκΉŒ?')) return;

        await fetch(`/api/users/${userId}`, { method: 'DELETE' });
        setUsers(prev => prev.filter(u => u.id !== userId));
    }, []);

    // 쑰건뢀 λ Œλ”λ§
    if (loading) return <div className="loading">λ‘œλ”© 쀑...</div>;
    if (error) return <div className="error">μ—λŸ¬: {error}</div>;

    return (
        <div className="user-list">
            <input
                type="search"
                placeholder="μ‚¬μš©μž 검색..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
            />

            <ul>
                {filteredUsers.map(user => (
                    <UserItem
                        key={user.id}
                        user={user}
                        onDelete={handleDelete}
                    />
                ))}
            </ul>

            {filteredUsers.length === 0 && (
                <p>검색 κ²°κ³Όκ°€ μ—†μŠ΅λ‹ˆλ‹€.</p>
            )}
        </div>
    );
}

// μžμ‹ μ»΄ν¬λ„ŒνŠΈ - React.memo둜 λΆˆν•„μš”ν•œ λ¦¬λ Œλ”λ§ λ°©μ§€
const UserItem = React.memo(function UserItem({
    user,
    onDelete
}: {
    user: User;
    onDelete: (id: number) => void;
}) {
    return (
        <li className="user-item">
            <span>{user.name}</span>
            <span>{user.email}</span>
            <button onClick={() => onDelete(user.id)}>μ‚­μ œ</button>
        </li>
    );
});
Custom Hook Pattern
// μž¬μ‚¬μš© κ°€λŠ₯ν•œ Custom Hook
import { useState, useEffect, useRef } from 'react';

// 데이터 페칭 Hook
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 controller = new AbortController();

        fetch(url, { signal: controller.signal })
            .then(res => {
                if (!res.ok) throw new Error(`HTTP ${res.status}`);
                return res.json();
            })
            .then(setData)
            .catch(err => {
                if (err.name !== 'AbortError') setError(err);
            })
            .finally(() => setLoading(false));

        return () => controller.abort();
    }, [url]);

    return { data, loading, error };
}

// 둜컬 μŠ€ν† λ¦¬μ§€ 동기화 Hook
function useLocalStorage<T>(key: string, initialValue: T) {
    const [storedValue, setStoredValue] = useState<T>(() => {
        if (typeof window === 'undefined') return initialValue;

        try {
            const item = localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch {
            return initialValue;
        }
    });

    const setValue = (value: T | ((val: T) => T)) => {
        const valueToStore = value instanceof Function ? value(storedValue) : value;
        setStoredValue(valueToStore);
        localStorage.setItem(key, JSON.stringify(valueToStore));
    };

    return [storedValue, setValue] as const;
}

// λ””λ°”μš΄μŠ€ Hook
function useDebounce<T>(value: T, delay: number): T {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
        const timer = setTimeout(() => setDebouncedValue(value), delay);
        return () => clearTimeout(timer);
    }, [value, delay]);

    return debouncedValue;
}

// μ‚¬μš© μ˜ˆμ‹œ
function SearchComponent() {
    const [query, setQuery] = useState('');
    const debouncedQuery = useDebounce(query, 300);
    const [history, setHistory] = useLocalStorage<string[]>('search-history', []);

    const { data, loading } = useFetch<SearchResult[]>(
        debouncedQuery ? `/api/search?q=${debouncedQuery}` : null
    );

    return (
        <div>
            <input
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder="검색어 μž…λ ₯"
            />
            {loading ? <p>검색 쀑...</p> : (
                <ul>
                    {data?.map(item => <li key={item.id}>{item.title}</li>)}
                </ul>
            )}
        </div>
    );
}

πŸ—£οΈ Examples of Practical Conversations

πŸ’Ό Project Kickoff
"Should we use React or Vue for the frontend stack of the new project?"

"Most of the team has React experience and the ecosystem is larger, so React would be a good choice. With Next.js, you get SSR and API Routes all at once, and it works well in combination with TypeScript. For state management, the combination of TanStack Query + Zustand is the current trend."
πŸ” Code Review
"Why does this component keep re-rendering? The props aren't changing..."

"Because the parent component is passing inline functions and objects as props. A new reference is created on every render, so React.memo doesn't work. You need to wrap them with useCallback and useMemo, or define the objects outside the component."
πŸ“± Technical interview
"Why is the Virtual DOM fast? Isn't it slower than manipulating the real DOM directly?"

"It's not that the Virtual DOM itself is fast; it's that change detection and minimization are fast. If a developer could manually perform optimized DOM manipulation, it could be faster, but it's easy to make mistakes and hard to maintain. React batches only the necessary changes with the Diffing algorithm, guaranteeing consistent performance."

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

⚠️ Cautions

  • useEffect dependency array - If you leave the dependency array empty, it runs only once on mount, but changes to the state or props used inside are not reflected. Do not ignore the ESLint exhaustive-deps rule.
  • Importance of the key prop - If you use index as the key when rendering lists, unexpected bugs occur when the order changes or items are inserted or deleted. Always use a unique id.
  • Excessive state lifting - If you lift all state to the top level, unnecessary re-renders occur. Keep state only in the nearest common ancestor that needs it.

πŸ”— Related Terms

πŸ“š Learn More