React
React.js
A UI library developed by Facebook. Component-based, with efficient rendering through the Virtual DOM. The most popular frontend tool.
React.js
A UI library developed by Facebook. Component-based, with efficient rendering through the Virtual DOM. The most popular frontend tool.
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.
// 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
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>
);
}
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free