Stores / Context
A Context is a mechanism for maintain application state in a way which is globally accessible to all components. We use them as intermediary layers to issue API calls to relevant services, and cache the results for [re]use. Though the thought may occur to use a plain JavaScript object to achieve state management, a React Context differs in one distinct ways:
- Properties are reactive. Changing Context values will automatically propagate to the component-level bindings which use them.
An application can have as many Contexts as needed to logically group state concerns. The Frontier CLI creates strongly typed Contexts, enabling full Intellisense and compiler support when writing code against them.
Usage
frontier mobile add store <store-name>
Example
frontier mobile add store auth
Output File
src/contexts/auth.context.tsx
Technical
Each generated serive is contained within the sub-folder src/contexts
directory. The context will provide high order functions that will help you to inject global state within you Class based components. It will also provide you will hooks for you to use in your function based components.
Member | Type | Description |
---|---|---|
ContextName ContextProvider | React Component | Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. |
ContextName Consumer | React Component | Allows components to subscribe to changes in the global state endpoint. |
withContextName | HOC^1 | Used when Class-based components would like to consume data from the a context |
useContextName | HOC^1 | Used when function-based components would like to consume data from the a contextresponse. |
ContextName
- This is the provided name for the context when created using the CLI'sadd
command above.- ^1HOC (High-Order Component) - a higher-order component is a function that takes a component and returns a new enhanced component.