react-smart-context
v0.1.0
Published
react-smart-context
Downloads
3
Readme
react-context-store
ReactSmartContext is a lightweight library that helps you use React Context efficiently and with less boilerplate code. Pass in an object of the initialState
and any methods you want and you'll receive an object of a Provider
component, Consumer
component, and withConsumer
HOC. See below for details.
For more information on why this is important, see this article by Ryan Florence.
Before
const ColorContext = React.createContext();
class ProviderWrapper extends React.Component {
state = {
color: 'orange',
setColor: (color) => {
this.setState({ color });
}
}
render() {
return (
<ColorContext.Provider value={this.state}>{this.props.children}</ColorContext.Provider>
);
}
}
const withConsumer = (WrappedComponent, providerName = 'provider') => (props) => (
<Consumer>
{(store) => <WrappedComponent {...{ [providerName]: store }} {...props} />}
</Consumer>
);
export { ColorContext.Provider as Provider, ColorContext.Consumer as Consumer, withConsumer };
After
const { Provider, Consumer, withConsumer } = createSmartReactContext({
initialState: { color: 'orange' },
setColor: (color) => ({ color }),
});
export { Provider, Consumer, withConsumer };