React 19 (RC version—as of September 2024) is the latest release of the popular web development library.
V19 is a significant milestone, bringing many new features and hooks. This post will discuss one of these hooks, the use
hook.
The use
hook
This hook allows developers to suspend the rendering of a UI component until an asynchronous task, such as fetching data or loading resources, is completed by suspending the received promise, without the need for complex state management.
Fetching data example
Our simple component follows the classic approach, using the useEffect
hook to fetch data from a mock API (MSW in my case). We manage the local state to store the data, along with isLoading and isError states to track the fetch status:
const [users, setUsers] = useState<any>(null);
const [isError, setIsError] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(true);
When the page first loads, we run this useEffect
hook to fetch the data, store it, and update the various states:
const fetchData = async () => {
const response = await fetch('/api/users');
return response.json();
};
useEffect(() => {
fetchData()
.then(setUsers)
.catch(() => setIsError(true))
.finally(() => setIsLoading(false));
}, []);
We show some UI while the request is being processed or if we encounter an error:
if (isLoading) {
return <h2>Loading...</h2>;
}
if (isError) {
return <h2>Error</h2>;
}
and finally! We render the users list:
return (
<>
{users.map((user) => {
return (
<div>
{user.lastName}, {user.firstName}
</div>
);
})}
</>
);
A lot of boilerplate code!
Now, let’s refactor!
Let’s remove the useState
and useEffect
hooks. We will keep the fetchData
method as it is.
Now we will fetch the data using the new use
hook, which takes a promise and returns either JSON data or an error:
const users = use(fetchData());
The way this hook works is similar to doing something like this:
const users = await fetchData();
Handling isLoading
and isError
To handle these state changes, we’ll go to our App component. We’ll use the React Suspense
component, which is designed to respond to asynchronous events. It displays a fallback UI until its children have finished loading.
For error handling when working with Suspense
, it’s common practice to use an ErrorBoundary
. We’ll add an ErrorBoundary
component that implements React’s getDerivedStateFromError()
method.
<ErrorBoundary fallback={<h2>Error</h2>}>
<Suspense fallback={<h2>Loading...</h2>}>
<UserList />
</Suspense>
</ErrorBoundary>
The refactor phase is completed!
Some extra’s
The usual rules for hooks do not apply here — you can use this hook anywhere you'd like!
Unlike regular hooks, the use hook can be used conditionally with an if statement, allowing you to decide whether to trigger it or not. For example, if you want to wrap a new API request with a feature flag and toggle it for testing, simply pass the feature flag to the UserList
component and wrap the use hook. It's that simple!
Let's modify the App
component:
<ErrorBoundary fallback={<h2>Error</h2>}>
<Suspense fallback={<h2>Loading...</h2>}>
<UserList testNewApi={true} />
</Suspense>
</ErrorBoundary>
Modify the UserList
component:
let users = [];
if(testNewApi){
user = use(fetchData());
}
You can also use this hook to obtain a Context
object, rather than using the regular method:
const data = useContext(myContext);
You can use the use
hook here, for example, if you want to retrieve the context based on a conditional statement.
Conclusion
In this article, I've outlined the syntax of the use
hook and provided usage examples. This should help you grasp this hook and how to use it effectively. I hope you find this information beneficial for your future projects.