React: Best practice of new React Context API

Created on 28 Feb 2018  路  3Comments  路  Source: facebook/react

New context API is really great, a lot of thanks for your efforts on this. It enabled us by a more efficient and easier way to write React app.

But, I still consider it as too much boilerplate/verbosity to use it on each leaf component. Everytime, you may write like this:

  funciton ContextWrapperComp() {
    return (
      <ThemeContext.Consumer>
        {({value}) => <RealComp value={value} />}
      </ThemeContext.Consumer>
    )
  }

So I published a npm package -- https://github.com/SunHuawei/with-context. I think it is the easiest way to use the new context API. You could use it as a decorator, like this:

// export withTheme in some place
import { withContext } from "with-context";
export const withTheme = withContext(ThemeContext, "theme");
// import withTheme, and use it anywhere
import { withTheme } from "./withTheme";

@withTheme
export default class LeafComponent extends React.PureComponent {
   ...
}

I'm not suggesting adding this as a official implement, nor you would do that I think. Just, please give it a try and tell me what do you think, really appreciate your attention.

Most helpful comment

Please don't use the issue tracker as a platform for sharing personal projects. We try to use it solely for bug reports and feature requests.

If you have a general usage question, please check our community support resources:
https://facebook.github.io/react/community/support.html

Thanks!

All 3 comments

@SunHuawei HOC api was discussed a lot of times in the original RFC. It was dismissed because of props collision. https://github.com/reactjs/rfcs/pull/2

@TrySound , OMG, I even did not noticed that. Thanks for your reminder.

But, I still think it is useful for someone. I want to hear more voice.

Please don't use the issue tracker as a platform for sharing personal projects. We try to use it solely for bug reports and feature requests.

If you have a general usage question, please check our community support resources:
https://facebook.github.io/react/community/support.html

Thanks!

Was this page helpful?
0 / 5 - 0 ratings