React Hooks는 클래스 컴포넌트에서 자주 마주치는 복잡성과 불편함을 해결하기 위해 개발된 기능입니다. Hooks의 특징과 장점, 클래스 컴포넌트와 함수형 컴포넌트 간의 차이를 살펴보겠습니다.
import React, { Component } from 'react';
import axios from 'axios';
class UserListClass extends Component {
state = {
users: [],
loading: true,
};
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then((res) => {
this.setState({ users: res.data, loading: false });
});
}
render() {
const { users, loading } = this.state;
if (loading) return <p>Loading...</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
}
기존의 함수형 컴포넌트는 클래스 컴포넌트에서 제공하는 생명주기(lifecycle) 메서드를 사용할 수 없어 제한적이었습니다. 하지만 React Hooks의 도입으로 함수형 컴포넌트에서도 컴포넌트 초기화 시점에 API 호출과 다양한 로직을 간단하게 처리할 수 있게 되었습니다.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const UserListFunction = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then((res) => {
setUsers(res.data);
setLoading(false);
});
}, []); // 빈 배열 → 컴포넌트 마운트 시 한 번만 실행
if (loading) return <p>Loading...</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
간결한 코드
성능 최적화
HOC 컴포넌트를 Custom Hooks로 대체
Custom Hooks를 사용하면 인증(auth), 데이터 요청(fetching) 등의 반복적 로직을 컴포넌트로부터 효과적으로 분리하여 관리할 수 있습니다. 이를 통해 각 컴포넌트는 UI와 핵심 기능 구현에만 집중할 수 있게 됩니다.
// useAuth.js
import { useState, useEffect } from 'react';
export const useAuth = () => {
const [user, setUser] = useState(null);
useEffect(() => {
// API 호출을 통해 사용자 정보 획득
fetchUser().then(setUser);
}, []);
return user;
};
// Profile.jsx
import React from 'react';
import { useAuth } from './useAuth';
const Profile = () => {
const user = useAuth();
if (!user) return <div>Loading...</div>;
return <div>Welcome, {user.name}</div>;
};
export default Profile;
React Hooks의 등장으로 클래스 컴포넌트에 비해 더 효율적이고 간결한 코드를 작성할 수 있게 되었으며, 이는 리액트 개발 환경의 혁신적인 발전으로 이어졌습니다.