use Promises

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional NextJS Lessons

1.Course Intro
free
⏱️ 2:05
2.Get Setup
free
⏱️ 2:05
3.Project Template
free
⏱️ 5:45
4.Introducing FullStack React
free
⏱️ 4:57
5.App Router Reference
free
⏱️ 7:08
6.NextJS Server vs. "use client" Rendering
⏱️ 5:01
7.Nesting Server and Client Components
⏱️ 8:51
8.Client Only Components
⏱️ 3:48
9.Global CSS in NextJS
⏱️ 6:30
10.CSS Modules and SASS
⏱️ 4:15
11.Tailwind CSS
⏱️ 5:17
12.NextJS Custom Fonts
⏱️ 4:08
13.Static vs Dynamic Rendering
⏱️ 4:55
14.NextJS Link Component
⏱️ 3:20
15.NextJS Link Prefetching
⏱️ 5:49
16.Navigation Scroll with Link
⏱️ 2:02
17.Replace Navigation History
⏱️ 1:35
18.NextJS Image Component
⏱️ 7:01
19.Dynamic Image URLs
⏱️ 5:34
20.Safe Colocation with Private Folders
⏱️ 2:12
21.NextJS Route Groups
⏱️ 3:07
22.Dynamic Routes
⏱️ 5:37
23.NextJS API Routes
⏱️ 6:03
24.NextRequest and NextResponse
⏱️ 2:41
25.Cookies in API Handlers
⏱️ 4:25
26.React Suspense Simplified
⏱️ 2:23
27.Power of Suspense Boundaries
⏱️ 3:52
28.use Promises
⏱️ 3:24
29.Stream Promise Results from Server to Client
⏱️ 3:03
30.use Requires a Cached Promise
free
⏱️ 2:30
31.Suspense Error Boundaries
⏱️ 4:42
32.React Server Functions
⏱️ 4:50
33.Server Actions for Powerful Forms
⏱️ 5:35
34.useActionState to Simplify Form Actions
⏱️ 6:38
35.React Serializable Types
⏱️ 2:42
36.Create Dynamic Images with NextJS ImageResponse
⏱️ 5:54
37.Deploy NextJS Application to Production
⏱️ 3:51
38.NextJS Environment Variables Masterclass
⏱️ 3:50
39.Deploying and Managing Environment Variables
⏱️ 4:38
40.Using Databases for Dynamic Server Side State
free
⏱️ 7:34
41.Mastering NextJS Layout Files
⏱️ 4:54
42.Client State Management with NextJS
⏱️ 3:48
43.Client State Management In Action
⏱️ 8:04
44.Using Client State Management Libraries
⏱️ 5:25
45.Detecting Server vs Client Runtime and useEffect
⏱️ 4:33
46.Demystifying ISR vs SSR vs SSG
⏱️ 3:07
47.Static Site Generation or SSG with NextJS
⏱️ 3:16
48.Incremental Static Regeneration (ISR) Simplified
⏱️ 2:51
49.API Routes Caching with NextJS
⏱️ 3:05
50.Reference Guide to Caching for Modern NextJS
⏱️ 2:47
51.Setup a BASE_URL for client and server
free
⏱️ 2:54
52.Creating a sitemap.xml
⏱️ 3:29
53.Provide metadata with NextJS
⏱️ 6:54
54.Created High Quality Social Media Previews
⏱️ 7:38

use Promises

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Modern React comes with a use API that provides a convenient way to effectively await a promise even when you cannot use async await.

Without use

We know that client components cannot use async/await. So if you wanted to make an api call from a place in your code where you cannot use async await, the code quickly gets out of hand.

For Example, making a simple api call to load prime factors:

"use client";

export function PrimeFactors({ input }: { input: number }) {
const [factors, factorsSet] = useState<[number, number] | null>(null);

useEffect(() => {
primeFactorsAPI(input).then(([factor1, factor2]) => {
factorsSet([factor1, factor2]);
});
}, [input]);

if (factors === null) {
return <PrimeFactorLoading />;
}

const [factor1, factor2] = factors;

return (
<div className={`bg-blue-300 ${styles.component}`}>
Prime Factors: {factor1} x {factor2}
</div>
);
}

Issues with this implementation:

  • This is a lot of code to effectively only achieve awaiting a promise
  • It locks the loading state into the component which makes it difficult to consolidate multiple loading states with a suspense boundary.
  • There are others ... but instead of boring you, lets just use use 😅

With use

React comes with a core use API that makes it trivial to await a promise and seamlessly integrate with React's Suspense API.

The same example as before is much simpler, declarative and composable (thanks to Suspense) when we utilize use.

ui/PrimeFactors.tsx
app/page.tsx
"use client";

import styles from "./primeFactorsStyles.module.css";
import { use } from "react";

export function PrimeFactors({
promise,
}: {
promise: Promise<[number, number]>;
}) {
const [factor1, factor2] = use(promise);

return (
<div className={`bg-blue-300 ${styles.component}`}>
Prime Factors: {factor1} x {factor2}
</div>
);
}
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Modern react comes with a use API that provides a convenient way to effectively await a promise even when you cannot use Async Await. For this example, we will use an external API that calculates the prime factors of a given input number. This API returns a promise and we plan to use it within the prime factors component. Note that this is a client component as indicated by the presence of a used client. What this means is that this component cannot be marked as async, which in turn means that we cannot simply make the API call and await its result.

00:31

So let's take a look at what we would need to do with traditional react. In order to make the API call and load its result, first we create a state variable with use state that will store the result. Once it arrives and initially we set it to null, then we utilize use effect to make that API call. Once a component is mounted. After that API returns with the result. We store it within our state variable, and for this use effect we depend upon the provided input prop. With this API call in place, before we return the final rendering, we first need to check if effect as is null.

01:04

If it is, then we are still waiting for that API to complete and therefore we return a loading screen. And if it is not null, it means that we have received the results and we simply render them out within our user interface. While at this point, we could continue to improve this code, but let's take a break and look at what this application looks like within the browser. Once the component is mounted, it makes that API call. And while that API call is still pending, we see a loading screen and after the API call is complete, we see the final fully rendered ui. There are a few issues with this implementation. First, there is a lot of code

01:37

to effectively only achieve awaiting a promise. Additionally, it locks the loading state into the component, which makes it difficult to consolidate multiple loading states. With the suspense boundary, these are exactly the kinds of problems solved by the use API, which React provides out of the box. We start off with a clean slate and bring in the use API from the core react module. Now, instead of accepting the final result, we accept the promise of the final result within the component, which in our case will be a promise of two numbers. Since we are in a client component,

02:09

we cannot simply await the promise. So instead, we use the use API provided by React. This is effectively the same as await. So we get back the final resolve value and from this point forward we can use it however we want. For example, simply render it within the return user interface. We still have to make the API call in order to create the promise, and we do that in the parent component. This ensures that the API call is made only once, and whenever the client component read ends, we don't end up making another API call. The question you should have at this point is,

02:41

what about our loading state? Well, fortunately, the use integrates with suspense the same way Async await integrated with suspense as we have seen before, which means that if you want to show a loading indicator for this component, we simply wrap it up with suspense providing a fallback. This has the advantages that we have Already covered in our lessons on suspense. For example, we can consolidate multiple loading states into a single coherent experience. Now, let's verify if the application still behaves as it did before, and no surprise we see the loading state while that component is waiting for the API call

03:14

and once it is returned, we see the final fully render ui and there is no doubt that this code is much more declarative and simpler than before. Thanks to use and suspense.

Professional NextJS

Professional NextJS

1.Course Intro
free
⏱️ 2:05
2.Get Setup
free
⏱️ 2:05
3.Project Template
free
⏱️ 5:45
4.Introducing FullStack React
free
⏱️ 4:57
5.App Router Reference
free
⏱️ 7:08
6.NextJS Server vs. "use client" Rendering
⏱️ 5:01
7.Nesting Server and Client Components
⏱️ 8:51
8.Client Only Components
⏱️ 3:48
9.Global CSS in NextJS
⏱️ 6:30
10.CSS Modules and SASS
⏱️ 4:15
11.Tailwind CSS
⏱️ 5:17
12.NextJS Custom Fonts
⏱️ 4:08
13.Static vs Dynamic Rendering
⏱️ 4:55
14.NextJS Link Component
⏱️ 3:20
15.NextJS Link Prefetching
⏱️ 5:49
16.Navigation Scroll with Link
⏱️ 2:02
17.Replace Navigation History
⏱️ 1:35
18.NextJS Image Component
⏱️ 7:01
19.Dynamic Image URLs
⏱️ 5:34
20.Safe Colocation with Private Folders
⏱️ 2:12
21.NextJS Route Groups
⏱️ 3:07
22.Dynamic Routes
⏱️ 5:37
23.NextJS API Routes
⏱️ 6:03
24.NextRequest and NextResponse
⏱️ 2:41
25.Cookies in API Handlers
⏱️ 4:25
26.React Suspense Simplified
⏱️ 2:23
27.Power of Suspense Boundaries
⏱️ 3:52
28.use Promises
⏱️ 3:24
29.Stream Promise Results from Server to Client
⏱️ 3:03
30.use Requires a Cached Promise
free
⏱️ 2:30
31.Suspense Error Boundaries
⏱️ 4:42
32.React Server Functions
⏱️ 4:50
33.Server Actions for Powerful Forms
⏱️ 5:35
34.useActionState to Simplify Form Actions
⏱️ 6:38
35.React Serializable Types
⏱️ 2:42
36.Create Dynamic Images with NextJS ImageResponse
⏱️ 5:54
37.Deploy NextJS Application to Production
⏱️ 3:51
38.NextJS Environment Variables Masterclass
⏱️ 3:50
39.Deploying and Managing Environment Variables
⏱️ 4:38
40.Using Databases for Dynamic Server Side State
free
⏱️ 7:34
41.Mastering NextJS Layout Files
⏱️ 4:54
42.Client State Management with NextJS
⏱️ 3:48
43.Client State Management In Action
⏱️ 8:04
44.Using Client State Management Libraries
⏱️ 5:25
45.Detecting Server vs Client Runtime and useEffect
⏱️ 4:33
46.Demystifying ISR vs SSR vs SSG
⏱️ 3:07
47.Static Site Generation or SSG with NextJS
⏱️ 3:16
48.Incremental Static Regeneration (ISR) Simplified
⏱️ 2:51
49.API Routes Caching with NextJS
⏱️ 3:05
50.Reference Guide to Caching for Modern NextJS
⏱️ 2:47
51.Setup a BASE_URL for client and server
free
⏱️ 2:54
52.Creating a sitemap.xml
⏱️ 3:29
53.Provide metadata with NextJS
⏱️ 6:54
54.Created High Quality Social Media Previews
⏱️ 7:38