🎨 프론트엔드 🌱 입문

React 18 완벽 가이드

React 18의 새로운 기능과 Hooks 완전 정복

⏱️ 10시간 👁️ 47 조회 ⭐ 추천 강좌
🎬 영상 강좌
📖 강좌 내용
# React 18 완벽 가이드

## 1. React란?
Facebook이 만든 UI 라이브러리. 컴포넌트 기반으로 재사용 가능한 UI를 구축합니다.

## 2. 프로젝트 생성
```bash
npx create-react-app myapp
cd myapp
npm start
```

### Vite로 생성 (더 빠름)
```bash
npm create vite@latest myapp -- --template react
cd myapp
npm install
npm run dev
```

## 3. 컴포넌트 기초
```jsx
// 함수형 컴포넌트
function Welcome({ name }) {
}

// 화살표 함수
const Button = ({ onClick, children }) => (
<button onClick={onClick}>{children}</button>
);

export default Welcome;
```

## 4. useState Hook
```jsx
import { useState } from "react";

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

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(prev => prev - 1)}>-1</button>
</div>
);
}
```

## 5. useEffect Hook
```jsx
import { useState, useEffect } from "react";

function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
});
}, [userId]); // userId가 바뀔 때마다 실행

if (loading) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
```

## 6. 조건부 렌더링
```jsx
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<button>Logout</button>
) : (
<button>Login</button>
)}

</div>
);
}
```

## 7. 리스트 렌더링
```jsx
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text}
</li>
))}
</ul>
);
}
```

## 8. 폼 처리
```jsx
function LoginForm() {
const [form, setForm] = useState({ email: "", password: "" });

const handleChange = (e) => {
setForm({ ...form, [e.target.name]: e.target.value });
};

const handleSubmit = (e) => {
e.preventDefault();
console.log(form);
};

return (
<form onSubmit={handleSubmit}>
<input name="email" value={form.email} onChange={handleChange} />
<input name="password" type="password" value={form.password} onChange={handleChange} />
<button type="submit">Login</button>
</form>
);
}
```

## 9. useContext (전역 상태)
```jsx
import { createContext, useContext, useState } from "react";

const ThemeContext = createContext();

function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}

function Button() {
const { theme, setTheme } = useContext(ThemeContext);
return <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>Toggle</button>;
}
```

## 10. Custom Hook
```jsx
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);

return { data, loading, error };
}

// 사용
function Users() {
const { data, loading } = useFetch("/api/users");
if (loading) return <p>Loading...</p>;
return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
```