Stores / Context
A Context is a mechanism for maintaining application state in a way that 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 way:
- 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
contexts/auth.context.tsx
Technical
Each generated service is contained within the sub-folder contexts
directory. The context will provide high order functions that will help you to inject global state within your Class based components. It will also provide you with 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 a context |
useContextName | HOC^1 | Used when function-based components would like to consume data from a context response. |
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.