esamattis / lean-redux

Redux state like local component state
https://epeli.github.io/lean-redux/examples/
MIT License
78 stars 3 forks source link
reactjs redux

Lean Redux Build Status

Redux state like local component state.

Design

Example

import {connectLean} from "lean-redux";

var Counter = ({count, handleClick}) => (
    <div>
        {count} <button onClick={handleClick}>+1</button>
    </div>
);
Counter = connectLean({
    getInitialState() {
        return {count: 0};
    },
    handleClick(e) {
        e.preventDefault();
        this.setState({count: this.state.count + 1});
    },
})(Counter);

// Scope it to a myCounter key in the Redux state
// <Counter scope="myCounter" />

To learn more checkout the live examples.

Setup

yarn add lean-redux

or

npm install --save lean-redux

Just add the leanReducer to your store and start creating components with connectLean.

import {createStore, applyMiddleware} from "redux";
import {Provider} from "react-redux";
import {leanReducer} from "lean-redux";

const store = createStore(leanReducer);

var Main = () => (
    <Provider store={store}>
        <Counter />
    </Provider>
);

ReactDOM.render(<Main />, document.getElementById("app"));

If you already have other reducers you can merge leanReducer into them with the composeReducers helper:

import {leanReducer, composeReducers} from "lean-redux";

const store = createStore(composeReducers(myReducer, myAnotherReducer, leanReducer));

Checkout the index.js in examples for complete example.

Usage with the Redux combineReducers helper

The combineReducers helper function does not like dynamically generated top level state keys so Lean Redux must be scoped under a specific key in the Redux state when used with the combineReducers helper.

import {createStore, combineReducers} from "redux";
import {leanReducer} from "lean-redux";

leanReducer.setGlobalScope("lean");

const store = createStore(combineReducers({
    lean: leanReducer
}));

API

Functions exported by the lean-redux module.

connectLean(options: Object): (component: ReactComponent) => ReactComponent

Connects a React component to a Redux store. Like connect() in React Redux it does not modify the component but returns a new one.

options

Any other methods are considered to be "handlers" and are passed to the wrapped component as props.

handlerContext

The context, this, in the handlers is like in the React Components.