React Context API + State Hook

React context and state hook are two new concept of the React API. This post show you how to mesh the two concepts together, so you can consume parent context in functional components.

Context API uses a provider/consumer pattern, which allow top level component to pass data to children. State hook let you augment functional (stateless) components and make them stateful. Here is a quick example of state hook from React docs. We will use this as the basis for context integration.

Mutating Context from Children

Previous example demonstrated a simple, one way context passing. If you have worked with Redux, or any global state managers, the next natural step is to mutate context from a child node.

The recommend pattern is to pass context mutator along with the context object. State hook also follow the same pattern, where useState returns a tuple of value and mutator. This makes a very natural integration between the two.

Note now the context object, CountCtx, is in the tuple form of [0, () => {}], where first element is the default value, and second is the mutator. The context provider, in turn, will pass down both state value and state mutator, <CountCtx.Provider value={[count, setCount]}>.