Ross Esmond

Code, Prose, and Mathematics.

portrait of myself, Ross Esmond
Written

Thunk Data Flow

A thunk can export data in two directions: to Redux as an action, and back to the calling function, presumably a component. When a thunk sends data to Redux, it may do so multiple times, whereas when it sends data back to its calling function, it must do so with either a return value or by throwing an error, which can only occur once. The ability to send data back to the calling function allows a React-thunk-Redux stack to keep Ephemeral Information in the component, rather than keeping all information in Redux, as with Saga.

Use Cases

There are many distinct use cases for sending data back to the calling function.

Using Redux as a server cache.

Say you’d like to use Redux as a smart cache of server resources, such that requests can return instantly if there is no reason to believe the result has changed from the last request. A request made through thunk may check the Redux store for the resources before fetching them from the web in order to selectively skin the request. If the resources are available and still considered valid, the thunk can return the value to the component, such that the component is not forced to rely directly on the Redux store.

If the component relies on the Redux store, than it must house the conditional logic to check the store for a resource, request the resource if it’s missing, and then track a loading state until the resource arrives. Whereas with thunk all of that logic simlifies to waiting on thunk, which either will or will not return immediately.

Storing errors in the component.

If a request times out, a thunk can throw an error which is caught by the calling component, such that the component may display an error without the error state being stored in Redux. This will allow the error state to be automatically cleaned up once the component leaves the screen, which is often preferable for most applications, as a failed form submission could be seen as ephemeral.

Tracking loading status in the component.

Similar to error states, a components ability to monitor the progress of a thunk allows the component to track the loading status of a resource. Even if the resource is ultimately stored inside of Redux, the component may still track its own loading state based on the resolution of the promise that Thunk provides.