Skip to content

Instantly share code, notes, and snippets.

@crash7
Created April 8, 2018 20:42
Show Gist options
  • Save crash7/583cc5216752f8033a4aa97197fc6240 to your computer and use it in GitHub Desktop.
Save crash7/583cc5216752f8033a4aa97197fc6240 to your computer and use it in GitHub Desktop.
Playing with the new React Context API
/**
* This a very small example of a HoC that used the new react context API that can be used to save a
* state globally without using any state library.
*
* This is a toy gist just to demo what you can do, please don't copy & paste the code without reading:
* https://reactjs.org/docs/context.htmt
*/
import React, { PureComponent } from 'react';
const defaultContextValue = {
something: "blue"
};
const { Provider, Consumer } = React.createContext();
export class DemoContextProvider extends PureComponent {
state = {
something: 'borrow',
doing: 0
}
constructor(props) {
super(props);
this.state.doSomething = this.doSomething
}
doSomething = () => {
this.setState((prevState) => ({ doing: ++prevState.doing }));
}
render() {
return (
<Provider value={this.state}>
{this.props.children}
</Provider>
);
}
}
export const withDemoContext = WrappedComponent => (props) => {
return (
<Consumer>
{context => <WrappedComponent {...props} demoContext={context} />}
</Consumer>
);
}
export default { DemoContextProvider, withDemoContext };
import { withDemoContext } from './DemoContext';
const StatelessButton = ({ demoContext }) => {
return (
<div>
it was called {`${demoContext.doing}`} times
<button onClick={demoContext.doSomething}>test</button>
</div>
);
}
const ThemedButton = withDemoContext(StatelessButton);
import { DemoContextProvider } from './DemoContext';
ReactDOM.render(
<DemoContextProvider>
<App />
</DemoContextProvider>,
document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment