Skip to content

Instantly share code, notes, and snippets.

@arlindosilvaneto
Last active May 8, 2019 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arlindosilvaneto/41834288e812c7cd9249684d29498381 to your computer and use it in GitHub Desktop.
Save arlindosilvaneto/41834288e812c7cd9249684d29498381 to your computer and use it in GitHub Desktop.
ReactJS Context API Provider with State and Consumer HOC
import React, { createContext } from 'react';
const UserContext = createContext();
export default class UserProvider extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {},
updateUser: this.updateUser
};
}
updateUser = (newUser) => {
this.setState({
user: newUser
});
}
render() {
return (
<UserContext.Provider value={this.state}>
{this.props.children}
</UserContext.Provider>
)
}
};
export const withUserContext = Inner => props => {
return (
<UserContext.Consumer>
{context => {
return <Inner user={context.user} updateUser={context.updateUser} {...props} />
}}
</UserContext.Consumer>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment