TL;DR — React introduced the
use hook and converted all its components into server first, which suspends your components until the promise/s has been resolved resulting in a much cleaner UI and no janky loading states.
If you’ve ever worked on a React or Next.js application, you’ve probably noticed that it’s pretty un-opinionated in general, particularly when it comes to dealing with asynchronous behaviors. However, the initial Server Components proposal made it difficult to access promise-based APIs.
React has finally acknowledged that async is an important part of developing applications on the web. Instead of having multiple useEffects or useSWRs and a ginormous loading hell, React finally decided to provide seamless integration to resolve promises by wrapping them in special bindings. Which is exactly what this article tends to talk about. So sit tight and let's get reacting!
- Introduces the
useunwraps the value of a promise, but it can be used inside normal components and Hooks, including on the client.
Read the full proposal here: First class support for promises and async/await
What does this mean for us?
In a typical React application, we would have components that are dependent on some data to be fetched and while that is done we usually go with a loading state which renders a spinner while our promise isn’t resolved, the child components also might have their own data fetching which would also require to be resolved, and thus a very janky UI.
Within React, we can leverage Suspense boundaries and have a tree of components that are all calling data, which needs to resolve promises at individual levels. We can just suspend at the top and let all of the promises below it resolve themselves, resulting in no more interruptions or flaky loading states.
With a significant change like this, React also announced that all its components are now server first by default until you choose for it to not be. You might be thinking now, what about
react-query our good old friend, well it helps us remove redundant local states we no longer need by leveraging API states instead, but it also returns a loading state, which no matter how optimized still doesn't keep us from defining the endpoint on the server.
The old vanilla way
A better way
The proposed way
React is bringing about a lot of change in the ecosystem by bringing about a new way of suspending and handling promises way above the tree and preventing loading propagation down the child component, resulting in faster hydration and removal of flaky loading hell.
This blog was originally posted in dev.to: https://dev.to/sayanide/react-just-got-awesomeer-349i
If I missed out on any point or you want to discuss something feel free to let me know.