React 16.7 alpha에서 Hooks 테스트해보기
배경
지난주 React Conf에서 발표된 Hooks가 alpha 버전으로 공개되어 개인 프로젝트에서 테스트해봤다. 현재 팀 프로젝트는 대부분 클래스형 컴포넌트로 작성되어 있고, 상태 관리를 위해 Redux를 사용하고 있다.
useState로 간단한 카운터 구현
기존 클래스형 컴포넌트를 함수형으로 변경해봤다.
// Before: Class Component
class Counter extends React.Component {
state = { count: 0 };
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.increment}>+1</button>
</div>
);
}
}
// After: Function Component with Hooks
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
}
코드가 확실히 간결해졌다. this 바인딩 문제도 자연스럽게 해결됐다.
useEffect로 사이드 이펙트 처리
API 호출이 필요한 컴포넌트에서 useEffect를 테스트했다.
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]);
if (loading) return <div>Loading...</div>;
return <div>{user.name}</div>;
}
componentDidMount와 componentDidUpdate 로직을 하나로 합칠 수 있어서 편했다. 의존성 배열로 조건부 실행도 깔끔하게 처리된다.
한계점
아직 alpha 버전이라 프로덕션 사용은 무리다. 16.7 정식 릴리즈를 기다려야 할 것 같다. 팀 내부적으로는 TypeScript 도입을 먼저 논의 중이라, Hooks는 그 이후에 검토할 예정이다.
결론
Hooks는 확실히 React 코드 작성 방식을 바꿀 잠재력이 있다. HOC나 Render Props 패턴의 복잡도를 줄일 수 있을 것으로 보인다. 정식 릴리즈 후 점진적으로 도입을 검토해볼 계획이다.