Skip to content
This repository was archived by the owner on Dec 31, 2020. It is now read-only.
This repository was archived by the owner on Dec 31, 2020. It is now read-only.

Idea: introduce <Inject store>{(store) => ... component, to mimic React.createContext's consumer #448

@danielkcz

Description

@danielkcz

This is merely just to start a discussion, but it's finally released in React 16.3. I think this can bring a huge relieve to all that inject mess, especially when in TypeScript.

First and foremost, given how beautifully crafted this new API is, it doesn't necessarily need to be a part of mobx-react anymore, but it probably should just for a convenience of a newcomer.

export function createConsumer<T>(stores: T) {
  const { Consumer } = createContext<T>(stores)
  return Consumer
}

// just use as a component
const Consumer = createConsumer(myStores)
<Consumer>{stores => /* inferred type, awesome */}</Consumer>

An alternative approach using a context.Provider is for cases when provided value is not constant, eg. in this case when a shape of the stores need to change. Personally, I haven't found any use case where that would be needed, so I am not going to elaborate on that futher. Also it's worth noting that there is no limit on calling that createConsumer function multiple times to have additional consumers with a separate stores.

The Consumer component can be used to create HoC variant. I am not entirely sure if all that logic that's currently present there is still needed. At least a ref handling can be done properly with a new forwardRef API. It's almost astounding seeing how much hassle is needed for that compared to a simple render prop case. Either way, I am not feeling confident enought to handle that.

Note: Typescript definition for createContext and forwardRef should be merged soon.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions