DEV Community

Discussion on: You don't have to use Redux

Collapse
 
jack profile image
Jack Williams

Great post!

We additionally use a HoC to make using the Context API easier. Something like this:

const withUser = (Component) => (
  (props) => (
    <UserContext.Consumer>
      {user => (
        <Component
          {...props}
          user={user}
        />
      )}
    </UserContext.Consumer>
  )
)
Enter fullscreen mode Exit fullscreen mode

Then to use it ...

const UserBookList = (props) => (/* props.user */);

export default withUser()(UserBookList);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anssamghezala profile image
Anssam Ghezala

Thank so much for sharing this !!! :DD

Collapse
 
jack profile image
Jack Williams

You're welcome, hope it helps!

The Context.Consumer code scattered everywhere felt clunky.

Collapse
 
patroza profile image
Patrick Roza • Edited

Would suggest to use useContext, either directly, or in the HOC:

const withUser = (Component) =>
  (props) => {
    const user = useContext(UserContext)
    return <Component {...props} user={user} />
  }
Collapse
 
jack profile image
Jack Williams

Yep you sure could! The original example was without hooks, so I went that route.