Unstated  —  The setState of React State Management

Written by Bram.us - - Aggregated on Monday March 12, 2018
Tags: elsewhere, context, link, react, state

Unstated is designed to build on top of the patterns already set out by React components and (the new) Context.

Unstated is built upon three pieces that all work together:

  1. Container
  2. <Subscribe>
  3. <Provider>

The idea is that the Container only keeps itself busy with the state. Using <Subscribe> you can link that state to your Component. The <Provider> wraps itself around everything, keeping things together.

import React from 'react';
import { render } from 'react-dom';
import { Provider, Subscribe, Container } from 'unstated';

type CounterState = {
  count: number
};

class CounterContainer extends Container<CounterState> {
  state = {
    count: 0
  };

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  decrement() {
    this.setState({ count: this.state.count - 1 });
  }
}

function Counter() {
  return (
    <Subscribe to={[CounterContainer]}>
      {counter => (
        <div>
          <button onClick={() => counter.decrement()}>-</button>
          <span>{counter.state.count}</span>
          <button onClick={() => counter.increment()}>+</button>
        </div>
      )}
    </Subscribe>
  );
}

render(
  <Provider>
    <Counter />
  </Provider>,
  document.getElementById('root')
);

Unstated — The setState of React State Management →
Unstated →


« Falcon Heavy & Starman - Bram.us

Bram.us - The exciting future of React »