/react-reducer-component

A tiny state management library using render props for react

Primary LanguageJavaScript

react-reducer-component

A tiny state management library using render props for react

npm CircleCI Greenkeeper badge

This is a implementation of the Reducer-Component pattern using render props.

Installation

Add react-reducer-component to your project.

yarn add react-reducer-component
npm i react-reducer-component --save

Usage

Import react-reducer-component

import ReducerProvider from "react-reducer-component";

Define a render prop and put your components in it. The first paramter is a function to update your app state via actions. The second parameter contains the app state, which you can pass as props to your components.

<ReducerProvider
  initialState={initialState}
  reducer={reducer}
  render={(reduce, props) => (<MyCustomCounter reduce={reduce} count={props.count} />)}
/>

Define your initialState, reducer und actions redux-style like so:

const initialState = {
  count: 0
};

// current state and an action in, updated state out
const reducer = (state = {}, action) => {
  if (action.type === INC_COUNTER) {
    return {
      ...state,
      count: state.count + 1
    };
  } else return state;
};

// simple example action
const INC_COUNTER = "INC_COUNTER";
const incCounter = () => {
  return {
    type: INC_COUNTER
  };
};

Use the provided reduce() function to update your state:

const MyCustomCounter = ({ reduce, count }) => (
  <button onClick={() => reduce(incCounter())}>{count}</button>
);

Full example

You can see a full example in example/