Showing the difference between Redux style and Suspense implementation.
This is eureka Advent Calendar 2019 3rd entry.
All client applications need loading indicators such as a rotating icon to indicate they are processing something like a web API request. Loading states need to be stored somewhere to implement that. If you used Redux, you use its state for that.
This entry shows how to convert a Redux style loading indicator to React Suspense style and what is different. The sample code is very similar to Suspense for Data Fetching. They explain common web API client implementation, and this entry is focused on implementation using Redux.
Loading indicator with Redux
The following sample application has a simple list of Eureka Engineering blog entries and a loading indicator that is shown while fetching.
Let’s imaging blog entries are loaded by a web API like RSS and its request status is stored in Redux state as ‘isLoading’. The loading indicator is shown while ‘isLoading’ is true.
The next image is an overview of this example. The ‘App’ component uses an operator to fetch entries witch changes ‘isLoading” and updates Redux global state. If then reads the ‘isLoading’ status from the global state in JSX to control which component should be used.
React Suspense is used in the next example. Is it different? Of course, it’s different. But these differences are very small.
First, a promise object is memoized to give the React Suspense a fallback. Second, changing component property type from “Entry” to “()=> Entry” to throw promise during blog entry loading and implementing “getEntries” as a function that is a satisfying Suspense specification. Finally “EntryList” component is surrounded by React Suspense with the “LoadingIndicator” component as a fallback.
This is an overview of this second application and not different from the previous overview. (Actually same image file)
These are only about 15 ~ 20 lines difference and also the same in the context of architecture.
What do these changes bring?
What do we get by using React Suspense? This answer is written in Suspense for Data Fetching
This doesn’t only remove boilerplate code, but it also simplifies making quick design changes.
(at the end of Approach 3: Render-as-You-Fetch using Suspense section)
Using Suspense make it easy to change the range of loading state by only changing the “Suspense” component position. We are free to consider which components have the same loading state and not.
This entry showed 2 points below.
- Suspense can be used with small changes.
- Suspense is useful to control the view of the loading state.
React development team announced Concurrent Mode and Suspense is a part of it. Concurrent Mode is a very challenging, interesting and little complex mechanism. Understanding Suspense is a good first step to understand Concurrent Mode.