react-smart-context

0.1.0 • Public • Published

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

/react-smart-context/

    Package Sidebar

    Install

    npm i react-smart-context

    Homepage

    honey.sh

    Weekly Downloads

    3

    Version

    0.1.0

    License

    MIT

    Unpacked Size

    33.4 kB

    Total Files

    7

    Last publish

    Collaborators

    • tibfib