DEV Community

Cover image for React 19 new features - the 'use' hook
Reuven Hozias
Reuven Hozias

Posted on

React 19 new features - the 'use' hook

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);
Enter fullscreen mode Exit fullscreen mode

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));
}, []);
Enter fullscreen mode Exit fullscreen mode

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>;
}
Enter fullscreen mode Exit fullscreen mode

and finally! We render the users list:

return ( 
  <>
    {users.map((user) => {
      return (
        <div>
          {user.lastName}, {user.firstName}
        </div>
      );
    })}
  </>
);
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

The way this hook works is similar to doing something like this:

const users = await fetchData();
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Modify the UserList component:

let users = [];
if(testNewApi){
  user = use(fetchData());
}
Enter fullscreen mode Exit fullscreen mode

You can also use this hook to obtain a Context object, rather than using the regular method:

const data = useContext(myContext);
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
savecohub profile image
Naz Hussain

Any idea how to downgrade from RC19 to 18.3?