Decouple Data from UI with React Hooks
And how I āprogram to an interfaceā with JavaScript functions

Iām certain you have seen (or written) this common React pattern: (a) render a placeholder/ loader/spinner while some data is fetched via AJAX, then (b) re-render the component based on the data received. Letās write a functional component leveraging the Fetch API to accomplish this.
Letās say my app grows, and there are X
components that use the same data fetching logic becauseā¦ reasons. To avoid spamming the server with data requests, I decide to use Local Storage to cache the data.
OKā¦ does that mean I need to update the data logic X
times? š¬š±
Nope, letās DRY it up by writing a custom hook useSomeData
.
The components that share this data logic now look concise.
OKā¦ DRY code is great, but so what?
Letās say my app becomes complex, so I decide to use Redux to handle AJAX requests and maintain a global app state. I simply update the implementation of useSomeData
without touching the UI components.
Then GraphQL comes along and I jump on the bandwagon. Again, I simply update the implementation of useSomeData
without touching the UI components.
Rinse and repeat whenever Iām compelled to update the data layer with the latest/hottest state management framework or API paradigm.
To me, this looks a lot like the classic Dependency Inversion Principle, the āDā in SOLID (check out this excellent explainer by Matthew Lucas). While this is not OOP by any means, where we formally define an abstract Interface
and create a concrete Class
that implements that Interface
, I would argue that there is a de facto āinterfaceā that useSomeData
provides to the various UI components using it. In this example, the UI doesnāt care how useSomeData
works, as long as it receives someData
, loading
, and error
from the hook.
So in theory, this frees the UI from being locked into any particular implementation of the data layer, and enables migrating to new implementations (frameworks/libraries/etc) without having to update the UI code, as long as the āinterfaceā contract is honored.
Curious to hear your thoughts.

P.S. The Container pattern, Render Props, and HOC are popular options to decouple the data layer from the UI layer for classical components. This article is not meant to be a debate as to whether Hooks is better or worse. Iām simply sharing how I learned to use Hooks to apply the same separation of concerns.