This guide demonstrates a React Pattern for sharing global state, without requiring any of the following:
- 😒 Prop-Drilling
- 🔥 Redux
- 💲 MobX
- 🏀 Apollo Link State
(The above emojis were auto-selected by Emoj)
The Context API
Recently I found myself at an Advanced React Training with Michael Jackson(no… not the King of Pop, the King of React Router 😉). We spent a good deal of the time working through Higher Order components and the new React Context API.
Being so new to The React Way, (yet so familiar with frameworks like Angular), I was surprised that React didn’t ship with any built-in service architecture. React is a very different beast to other frameworks. It is intentionally designed to be all-state and no-service.
If you want to learn more about the React Context API, I recommend reading:
- Docs: The React Context API
- Blog: How to use the new React Context API
I found this blog post easier to understand than the examples in the React documentation — perhaps because I’m still on the React learning curve.
IMO: The fact that React is now shipping the Context API as a first-class citizen, means that a subscribing to global state (to use the term loosely), is no longer considered an anti-pattern. React is now providing a de-facto way of sharing state within the React tree without some of the limitations of higher order components.
“Unstated” Dependency Injection
But, the React Context API does not provide a method of dependency injection.
Dependency injection would allow us to instantiate multiple copies of a component with a discrete state that can be provided and consumed at any point in the app.
This pattern is useful for:
- Identical components that subscribe to different data sources with the same model, using the same methods and state properties
- Testing snapshots with mock states
Thankfully, there is “Unstated“— a tiny dependency that provides a handy wrapper around the Context API for dependency injection. I want to encourage you to read the Unstated documentation and get a feel for what it does, as I will be using it in the code examples below: Unstated README.md
To Continue Reading the post on https://hmh.engineering/the-unstated-react-service-pattern-786ea6168d1d