React Hooks 깊이 파헤치기
0회 조회
React Hooks 깊이 파헤치기
Hooks는 함수 컴포넌트에서 상태와 사이드 이펙트를 관리하는 방법입니다.
useState - 상태 관리
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(prev => prev + 1)}>
증가
</button>
</div>
)
}
팁: 이전 상태를 기반으로 업데이트할 때는 함수형 업데이터를 사용하세요.
useEffect - 사이드 이펙트
import { useState, useEffect } from 'react'
function UserProfile({ userId }: { userId: number }) {
const [user, setUser] = useState<User | null>(null)
useEffect(() => {
let cancelled = false
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
if (!cancelled) setUser(data)
})
// 클린업 함수
return () => { cancelled = true }
}, [userId]) // userId가 바뀔 때마다 재실행
if (!user) return <div>Loading...</div>
return <div>{user.name}</div>
}
useReducer - 복잡한 상태
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'reset' }
function reducer(state: number, action: Action): number {
switch (action.type) {
case 'increment': return state + 1
case 'decrement': return state - 1
case 'reset': return 0
}
}
function Counter() {
const [count, dispatch] = useReducer(reducer, 0)
return (
<div>
<p>{count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
)
}
성능 최적화 Hooks
| Hook | 용도 | 언제 사용? |
|---|---|---|
useMemo |
값 메모이제이션 | 비용이 큰 계산 |
useCallback |
함수 메모이제이션 | 자식에 콜백 전달 시 |
useRef |
렌더링 없이 값 보존 | DOM 참조, 타이머 ID |
const expensiveValue = useMemo(() => {
return items.filter(item => item.active).length
}, [items])
const handleClick = useCallback(() => {
onSelect(item.id)
}, [item.id, onSelect])
Hooks의 규칙을 지키고, 의존성 배열을 올바르게 관리하는 것이 핵심입니다.