Creating a Shared and Cached Fetch Request

Posted in Engineering

Shared Parallelism

There are cases when you have multiple components that display the same data from the same source. If every component that requests the data need to fetch it from the source, you would end up with too many fetch request; thus consuming many of the user network resources.

Typically, this can be solved by requesting the data only once on the parent component, then pass down the data to the components that might need it. However, now you have to responsibly manage the state of the data on the parent component and pass it around.

What if we could reuse the same code, that it is written like every component is requesting the data, but the data was actually shared and cached instead of fetching it every time from the source?

The concept is simple, wrap the fetch call into a function that handles sharing fetch state and cache expiration.

You can play with this example on https://codesandbox.io/s/shared-cached-fetch-9szql

Another Approach

What do you think about this approach? Do you have a better alternative or addition to this implementation? Feel free to share your thoughts!

I remember using saga patterns that handle this kind of issue, but adding a whole saga pattern seems like an overkill for my small project.