Reputation: 7672
I know React suspense is new and hasn't been officially released for production yet but I was wondering what the main benefits of it are/or using it would be?
I can't see anything it does as being "new" or replacing something that doesn't already exist?
I know it allows me to load stuff from top to bottom but I can do that anyway in react using my own components
can anyone give me some ideas as to what it may be good for?
Upvotes: 2
Views: 1416
Reputation: 3118
First of all, I would like to mention that Suspense is officially released since React 16.6. It is production-ready and it is not limited only to code-splitting. Any asynchronous code can be integrated with it.
As of the benefits, consider the following use-case:
The good old way of doing this would be:
Does this all look like unnecessary, hard to change boilerplate? Yes, it does).
React introduced the Suspense component and Error Boundaries to eliminate this boilerplate and to declaratively describe the desired behavior.
Check this out:
<Exception fallback="An error has occured">
<Suspense fallback="Loading...">
<OurComponent1 />
<OurComponent2 />
<OurComponent3 />
</Suspense>
</Exception>
Suppose we want to fetch users' data from the remote resource.
const fetchUsers = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const users = await response.json();
console.log("Users data", users);
return users;
};
I will use makeSuspendableHook to integrate our asynchronous fetch within <Suspense>
and Error boundary.
const useUsers = makeSuspendableHook(fetchUsers());
In our component, all we should care about is the actual data and its representation.
const Users = () => {
const users = useUsers();
return (
<div>
List fetched users:
<ul>
{users.map(({ name }) => (
<li>{name}</li>
))}
</ul>
</div>
);
}
Finally, I will use Exception as an Error Boundary implementation to stitch everything together.
export default () => (
<Exception fallback="An error has occurred">
<Suspense fallback="Waiting...">
<Users />
</Suspense>
</Exception>
);
Play with web example at codesandbox.io
Play with native example at snack.expo.io
Upvotes: 1
Reputation: 7460
it has several benefits to use:
async
components so easily event with a simple UI ( imagine instead of created a loading login by useState
Api or something else ) these were just simple benefits of Reacts Suspense/lazy
api.
Upvotes: 2