banner
News center
In-depth experience and state-of-the-art facilities

React's use() Hook: How to Apply It and Why

Oct 28, 2023

This new hook can help simplify a lot of boilerplate code.

The React apps you develop will often fetch data from an external API, and the React team has made sure to cater to this need. The use() hook simplifies the process of data fetching.

Using this hook, you'll reduce the amount of boilerplate code you need to define promises and update application state. Learn all about React's use() hook and how to use it in your React projects.

Consider the following component, for example:

Once React renders this component, it consumes the API using fetch(). It then either saves the data to the component's state if the request was successful, or sets the isError variable to true if it wasn't.

Depending on the state, it then renders either data from the API or an error message. While the API request is pending, it shows a "Loading..." text on the page.

The above component is a bit cumbersome since it's full of boilerplate code. To solve this problem, bring in the use() hook and refactor your code.

With the use() hook, you can reduce the above component to just two lines of code. But before doing that, note that this hook is rather new so you can only use it in the experimental version of React. So make sure you're using that version:

You're now ready to use the hook, starting by replacing the useState and useEffect imports with just use:

Inside the Data component, the only thing you're going to keep is the fetch request. But you'll need to wrap the fetch request inside your use() hook; it returns either JSON data or an error. Then set the response to a variable called data:

That's all! As you can see, the above code reduces the component to just two lines of code. That demonstrates just how useful the use() hook can be in scenarios like this.

An important part of the use() hook is handling the loading and error states. You can do this inside the parent component of Data.

To implement the loading functionality, wrap the Data component with Suspense. This component takes a fallback prop that it will render anytime you're in the loading state:

The use() hook in the Data component triggers this suspense to load. While the promise is yet to resolve, the App component will render the fallback state. Then, when the Data component receives the response data, it renders the content instead of the loading state.

When it comes to catching errors, you need to know how Error Boundary works to use it. Typically, you'll use it when you're working with Suspense.

An example of an Error Boundary is in the following code:

This Error Boundary example has a state object that tracks the error state and what the error is. Next, it gets the derived state from that error. The render() function displays the fallback element if there's an error. Otherwise, it renders whatever is inside the <ErrorBoundary />.

The above component works pretty much the same as Suspense. So, in the App component, you can wrap everything inside the ErrorBoundary component like so:

If any of the nested code throws an error, your Error Boundary will catch it via getDerivedStateFromError() and update the state, which in turn renders the fallback text, "Oops! There's an error."

So the use() hook can help to reduce the amount of boilerplate code, and facilitates loading and error states. But the use() hook also has another very handy use.

Let's assume that you're sending a shouldFetch boolean as a prop to the Data component, and you only want to run the fetch request if shouldFetch is true.

You can't wrap the traditional React hooks inside an if statement, but the use() hook is different. You can use it pretty much anywhere you want (wrapped in a for loop, if statement, etc.):

With the above code, React will render "Default data" by default. But if you tell it to do a fetch by passing the shouldFetch prop from the parent, it'll make the request and assign the response to data.

Another interesting thing about the use() hook is that you don't just have to use it with promises. For example, at the time of writing, you can pass in a context:

While using the useContext() is perfectly fine, you can't use it inside if statements and loops. But you can wrap the use() hook inside if statements and for loops.

The use() hook is just one of the many hooks provided by React. Familiarizing yourself with these hooks and how best to use them is essential for improving your React knowledge.

Kingsley is a freelance web developer from Nigeria. He has been writing JavaScript and Node.js professionally for over 3 years. During this time, he has worked with clients from all across the globe. Kingsley also educates developers via his writing. He writes for several tech-based publications and agencies, including FreeCodeCamp, Tutsplus, ContentLab, and MakeUseOf.

use()use()isErroruse()useStateuseEffectuseDatause()datause()DataDataSuspenseuse()AppDatarender()<ErrorBoundary />ErrorBoundarygetDerivedStateFromError()shouldFetchDatashouldFetchtrueifuse()forifshouldFetchdatause()