Code example: The use hook RFC | Aakash Bhardwaj

Post

editor-img
Aakash Bhardwaj
Oct 26, 2022

Code example: The use hook RFC

Hey,

In the last post, I talked about the use hook RFC. In today's post, I will share a code example.

const PostsList = () => { const posts = use(fifoPostsAPI.get()) return (<div> {posts.map(post => (<p id={post.id}>{post.name}</p>))} </div>)}

In the code snippet above, just like await, use effectively unwraps the value of the Promise returned by our fifoPostsAPI. Unlike await however, the execution of the component is not actually resumed from the same place when the Promise is resolved.

Instead, use throws an exception, just like React.Suspense to interrupt the rendering. When the promise resolves, the component is re-rendered:

When the promise finally resolves, React will replay the component’s render. During this subsequent attempt, the use call will return the fulfilled value of the promise.

So that's how it will be implemented. Hope you had fun reading this. Have a great day ahead. See you later, alligator! 🐊