Skip to content

Best practice of new React Context API #12306

@SunHuawei

Description

@SunHuawei

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions