The use Hook
Promises and context.
React nineteen added a hook simply called use. It reads a value from a promise or a context. Unlike other hooks, it can even be called inside an if.
- A hook called use
- Promises and context
- Even inside if
Reading a promise
Use reads a promise during render. While it's pending, the component suspends, and the nearest suspense boundary shows its fallback. The promise is created once, outside the component, so it isn't recreated every render. Use can also read context, and unlike other hooks, it can be called inside an if. Run it.
import { use, Suspense } from "react";
import { getProducts } from "./api";
const productsPromise = getProducts();
function ProductList() {
const products = use(productsPromise);
return <ul>{products.map(p => <li key={p.id}>{p.name} — £{p.price}</li>)}</ul>;
}
export default function App() {
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductList />
</Suspense>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses api.js
const PRODUCTS = [
{ id: 1, name: "Trail 500", price: 849.5, type: "bike", stock: 12 },
{ id: 2, name: "City 200", price: 450, type: "bike", stock: 0 },
{ id: 3, name: "Volt 7", price: 2199, type: "bike", stock: 4 },
{ id: 4, name: "Helmet", price: 40, type: "gear", stock: 30 },
{ id: 5, name: "Lights", price: 25, type: "gear", stock: 18 },
];
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
export async function getProducts() {
await wait(300);
return PRODUCTS;
}
export async function getProduct(id) {
await wait(300);
const product = PRODUCTS.find(p => p.id === Number(id));
if (!product) throw new Error(`Product ${id} not found`);
return product;
}Also uses actions.json
[{"wait": 600}]Stable promises
Don't create the promise inside the component, or every render makes a new one, and it suspends forever. Create it outside, or get it from a framework or a data library, which caches it for you.
| key | value |
|---|---|
| Inside render | new promise each time |
| Outside | stable |
| Frameworks | cache it |
| Also reads | context |
Summary
Use reads promises and context, and works with suspense. Next, a new section on performance.
Key takeaways- use(promise)
- use(Context)
- Suspense