1.0.1 • Published 9 years ago

react-stateful v1.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
9 years ago

No Maintenance Intended

No Maintenance Intended

This project is no longer maintained. It does its job, but there are no plans to extend or change it.
We don’t recommend you to depend on it, but you are free to reimplement a similar idea if you’d like.

react-stateful

The last enemy that shall be destroyed is this.
— An old JavaScript tutorial

A higher-order React component for lifting simple state and keeping your components pure.

This API is tiny and experimental.
It may change a lot, or I may abandon it in the future. Feel free to play with it now!

Why

You want to move the state out of your own components and rely on props as much as possible.
You want to keep all possible mutations of your component's state declarative, co-located, and named.

Why Not

This won't help you with data subscriptions a la Flux.
We're only talking about local component UI state.
This also won't work with props triggering a state change (at least, not yet).

Inspiration

This repo was inspired by react-controllables and Reduce State proposal from react-future.

Usage

This example assumes ES7 decorators (Babel supports them with "stage": 1). However they're easy and clean to write in desugared form, so try Babel REPL if you're curious.

import React, { PropTypes } from 'react';
import Stateful from 'react-stateful';

// So what's your state like?
const CounterState = {
  // like getInitialState
  initialize(props) {
    return {
      counter: 0
    };
  },

  // kinda like Flux actions
  reducers: {
    // how does your state change?
    increment(props, state) {
      return {
        counter: state.counter + 1
      };
    }
  }
};

@Stateful(CounterState) // injects state and reducers as props! component stays pure.
class Counter {
  static propTypes = {
    counter: PropTypes.number.isRequired,
    increment: PropTypes.func.isRequired
  };

  render() {
    const { counter, increment } = this.props;
    return <div onClick={increment}>{counter}</div>;
  }
}

export default class App extends React.Component {
  render() {
    return (
      <Counter />
    );
  }
}
1.0.1

9 years ago

1.0.0

9 years ago