티스토리 뷰
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
'React.js' 카테고리의 다른 글
[React.js] useOptimistic에 대하여 (0) | 2025.07.20 |
---|---|
[React.js] react-three/cannon을 활용하여 주사위 굴리기 구현하기 (0) | 2024.07.16 |
[React.js] Raect-three-fiber 알아보기 (0) | 2024.07.14 |
[React.js] React와 EventEmitter3를 활용하여 STOMP WebSocket 메시지 처리하기 (0) | 2024.06.04 |
[React.js] React.js에서의 클로저(컴포넌트 상태 관리의 이해) (0) | 2024.05.21 |
- Total
- Today
- Yesterday
- useoptimistic
- baekjoon
- react-query
- stompjs
- React.JS
- useMemo
- js
- react-quey
- 24431
- revalidateTag
- 해시를 사용한 집합과 맵
- 20551
- RefreshToken
- eventemitter3
- useCallback
- 4659
- useQuery
- react-three-fiber
- rc-dock
- 백준
- Next.js
- 9575
- NextAuth
- sepolia
- zustand
- useMutation
- 25329
- react19
- React
- revalidatePath
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |