Context
WebComp's Context is a way to manage a shared state across components
Sometimes you need to do more than just sending events between components. In some cases you might want a way to manage shared state between multiple components. You can do it using WebComp's Context.
Using Context
Here's how to use WebComp's Context
1. Import context
2. Wrap your component in withContext
before registering
withContext
before registering3. Get context from props
Once rendered, context-enabled component will have access to this.props.context
which is an array with a value and a function to set that value:
Initial context value
By default, any context value you use is going to be set to null
on the initial render. You can override this behavior in one of the two ways:
Second argument in withContext
withContext
getInitialContext
static method
getInitialContext
static methodYou can also specify a static method to provide initial data for the context
You can return a promise in getInitialContext
, but keep in mind that it may result in a content flash if you have async operations in getInitialContext
that take too long.
Note: Keep in mind, that both withContext
initial value and getInitialContext
are only used if the context value doesn't exist. If it has been populated before, they will be ignored.
Last updated