[React.js] use에 대해 알아보기
use란?
리액트 19 버전에 새롭게 추가된 훅으로 Promise나 Context와 같은 데이터를 참조하는 React API입니다.
기존의 복잡한 상태 관리 코드를 대폭 간소화하면서도, Suspense와 Error Boundary와의 완벽한 통합으로 더 나은 사용자 경험을 제공합니다.
import { use } from 'react';
function MessageComponent({ messagePromise }) {
const message = use(messagePromise);
const theme = use(ThemeContext);
// ...
use 훅으로 데이터 불러오기
기존 방식
const getMockDataAxios = async () => {
const response = await axios.get<User[]>(
`https://${process.env.NEXT_PUBLIC_API_KEY}.mockapi.io/api/v1/users`,
);
return response.data;
};
function Example() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const fetchUsers = async () => {
try {
setLoading(true);
const response = await getMockDataAxios();
setUsers(response.data);
} catch (err) {
setError(err as Error);
} finally {
setLoading(false);
}
};
fetchUsers();
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
...
);
}
기존의 useState와 useEffect를 조합해서 데이터 페칭을 처리하던 방식과 달리, Promise를 직접 사용할 수 있어 코드가 더 간결해집니다.
use 훅 사용
import { ErrorBoundary } from 'react-error-boundary';
import { use, Suspense } from 'react';
import axios from 'axios';
const getMockDataAxios = async () => {
const response = await axios.get<User[]>(
`https://${process.env.NEXT_PUBLIC_API_KEY}.mockapi.io/api/v1/users`,
);
return response.data;
};
function UseHookExample() {
// use 훅으로 Promise를 직접 사용
const users = use(getMockDataAxios());
return (
...
)
}
export default function UseHookExample() {
return (
<ErrorBoundary fallback={<div>에러가 발생했습니다.</div>}>
<Suspense fallback={<div>Loading</div>}>
<UseHookExample />
</Suspense>
</ErrorBoundary>
);
}
특징
use 훅에 Promise를 전달하면, React는 자동으로 Suspense와 Error Boundary와 연동하여 데이터 페칭을 처리합니다.
로딩 상태 처리 (Suspense)
- Pending 상태: Promise가 아직 완료되지 않은 동안, use 훅을 사용하는 컴포넌트는 자동으로 Suspend됩니다
- Fallback 표시: 컴포넌트가 Suspense 경계로 감싸져 있다면, 로딩 중에는 지정된 fallback UI가 표시됩니다
- 자동 전환: Promise가 resolve되면 fallback이 실제 컴포넌트로 자동 교체됩니다
use 훅으로 Context 불러오기
function Example() {
const theme = use(ThemeContext);
return (
...
);
}
Context가 use에 전달되면 useContext와 유사하게 작동합니다. useContext는 컴포넌트의 최상위 수준에서 호출해야 하지만, use는 if와 같은 조건문이나 for와 같은 반복문 내부에서 호출할 수 있습니다. use는 유연하므로 useContext보다 선호됩니다.
조건부 Context 사용
function Example({ show }) {
if (show) {
const theme = use(ThemeContext);
return (
...
);
}
return false;
}
참고
https://ko.react.dev/reference/react/use
use – React
The library for web and native user interfaces
ko.react.dev