React 상태 관리 방법 비교해 줘. useState, Context, 외부 라이브러리 중에 뭘 써야 해?
상태가 어디까지 퍼지는지로 고르면 쉬워요.
| 방법 | 잘 맞는 곳 | 조심할 점 |
|---|---|---|
| useState | 한 컴포넌트 안의 값 | 여러 곳에 내려 주면 props가 길어져요 |
| Context | 테마, 로그인 사용자처럼 드물게 바뀌는 값 | 값이 바뀌면 아래가 모두 다시 그려져요 |
| 외부 라이브러리 | 여러 화면이 자주 함께 바꾸는 값 | 배울 것과 의존성이 늘어요 |
처음에는 useState로 시작하고, 불편해질 때 한 단계씩 올리세요.
가장 작은 예는 이래요.
tsx
import { useState } from "react";
export function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>{count}</button>;}직접 눌러 볼 수 있게 같은 카운터를 HTML로도 만들었어요.
html
<!doctype html><html lang="ko"><body style="font-family: system-ui; display: grid; place-items: center; height: 100vh; margin: 0"> <div style="text-align: center"> <p id="n" style="font-size: 48px; margin: 0 0 12px">0</p> <button id="b" style="font-size: 16px; padding: 8px 20px">하나 더하기</button> </div> <script> let n = 0; document.getElementById("b").onclick = () => { n += 1; document.getElementById("n").textContent = n; }; </script></body></html>Deep
Claude와 관계없는 연습용 서비스예요. 데이터는 모두 예시예요.
Claude와 관계없는 연습용 서비스예요. 데이터는 모두 예시예요.