What are micro contexts? It is a way to create a nice separation of domains and group together data.
Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.This is pretty awesome, because we now have a native way to manage our global state, page-level state, etc, which is what I use it for quite a bit. But recently I had a project where I created some local context that I just called a Micro Context. Sounds fancy but it is pretty simple. Pretty much, this context accepted the data structure for a particular domain object, then exposed that data to all the children, the best part, I could then create a BUNCH of utility hooks to access this context data and do something with it. It made working with the data much easier, made my components really clean and allowed me to reuse the context & hooks to various parts of the application, a win-win really. Another benefit was, the context was now really close to where it was being used, which is ideal. Obviously, you want to see an example. Lets do it, I am going to use a e-commerce site as an example, specifically for a grocery store in my case, I live in Australia, so I have to use Woolworths. (And yes, opening to the coffee and tea page was intentional)
Product
micro context.
ProductProvider
, so each one of those components can access the data that it needs and decide if it should render or not. We don’t have to do anything special in this card, simply just construct the layout. What makes this really nice, we can pretty freely remove or add sections of the card. Allowing us to use the same provider, same components to construct a smaller card, landscape card etc.
To render these we’d just do;
useProductTitle
- combines the title
+ quantity
into one stringuseProductDiscountAmount
- checks if the product is on sale then returns the difference between price
and onSalePrice
.Product
), meaning wherever a product is rendering data, you can wrap it in the context and use a large collection of hooks to make the data manipulation constant and easy.