Hacker News new | ask | show | jobs
by jerrycruncher 2474 days ago
Sure. The app I'd been working on had previously been using the original 'render prop' style of accessing context in functional components and using the this.contextType accessor for class-based components. Both approaches had their downsides:

- 'render props' are fairly awkward to write, and add a lot of noise to a component that's working with data from multiple contexts.

- this.contextType can only give a component access to one context. This is a pretty big problem.

With Hooks, useContext lets you reference and destructure contexts in a really elegant way. Say you want to show a user's name if they're logged in, with the render prop approach it's something like:

  <AuthContext.Consumer>
    {({ isLoggedIn } => {
      return (<div> {isLoggedIn && <span>i'm logged in</span>} </div>)
    })}
  </AuthContext.Consumer>
with useContext, you can do

  const { isLoggedIn } = useContext(AuthContext);
and then use

  {isLoggedIn && ...} 
to condtionally render anywhere in the body of your component without all the Context.Consumer business.
1 comments

Was there ever any clarification on why the React team went with a single `contextType`, and not something like:

    class MyComponent extends Component {
      static contextTypes = {
        auth: AuthContext,
      }
    }