0.1.0 • Published 6 years ago

react-smart-context v0.1.0

Weekly downloads
1
License
MIT
Repository
-
Last release
6 years ago

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 };
0.1.0

6 years ago