One of the new features in React 19 is the use
API.
The basic idea is that the use
API can fetch resources during React's render cycle. Instead of doing something like fetching data in an effect and updating the component state, we can get the data directly via the use
API.
When paired with React's Suspense
component, we can easily manage conditional rendering:
In the example above, the App
component gets a getCommentsPromise
, which is eventually passed to the use
API in the Comments
component. The promise takes some time to resolve, which means we should probably show a loading state.
The good news is that we don't have to manage this ourselves. Because the use
API works seamlessly with the Suspense
component, we can provide a fallback
and things just work!
Context values can be conditionally loaded with the use
API.
Normally, you would need to use the useContext
hook to get the value of a Context provider. The problem with this approach is that this hook has to follow the Rules of Hooks.
The relevant rule is that we can't call a hook conditionally.
The use
API, on the other hand, doesn't have this restriction. We are free to load a Context value however we want:
In this example, notice how the UserBanner
component reads the UserContext
value if the showUser
prop is true
. In other words, if this prop is false
, then we don't call the use
API.
This is the key difference!
If we were to use the useContext
hook, then we wouldn't be able to do this. We would have to put the hook at the top of the component and always read the context value regardless of whether we use it in the final JSX.
How do you handle errors?
So what if the resource you're loading throws an error? Maybe there's an auth error or a timeout. The good news is that handling an error with the use
API is straightforward!
You have two main options:
Use an error boundary
Catch the error and return a different value
Here's an example using an error boundary:
import { use, Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
export function Comments({ getCommentsPromise }) {
return (
<ErrorBoundary fallback={<p>Oh no! Something went wrong!</p>}>
<Suspense fallback={<p>Fetching Comments!</p>}>
<Comment commentPromise={getCommentsPromise} />
</Suspense>
</ErrorBoundary>
);
}
function Comment({ commentPromise }) {
const comment = use(commentPromise);
return <p>{comment}</p>;
}
The use
API must be called within the render cycle.
One thing to keep in mind is that the use
API has to be called in a component's render cycle. This is similar to hooks. The key difference is that you can leverage the use
API conditionally. Outside of that, you can also easily manage loading and error states.
And that's it!
React 19's use
API is a simple and powerful tool to handle loading data asynchronously, loading context values, and conditionally rendering JSX.