Skip to content

rjz/typescript-react-reducer-component

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TypeScript React Reducer Components

A minimal state container inspired by Reason's state reducers, adapted for TypeScript.

Usage

Using the example factory in src/reducerComponent, creating new reducer components is as easy as 1, 2, 3...

  1. Declare State and Action types for the component.
type Action =
| 'INCREMENT'
| 'DECREMENT';

type State = {
  count: number,
};
  1. make the component from a reducer and a rendering function.
import * as RC from './reducerComponent';

const Counter: RC.Component<Action, State> = ({ count, send }) => (
  <div>
    <h1>Count: {count}</h1>
    <div>
      <button onClick={() => send('INCREMENT')}>+1</button>
      <button onClick={() => send('DECREMENT')}>-1</button>
    </div>
  </div>
);

const reduce: RC.Reducer<Action, State> = (state, action) => {
  switch (action) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

export default RC.make(reduce)(Counter);
  1. Profit

Example

$ yarn
$ yarn start

License

ISC

About

A minimal React state container, written in TypeScript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published