• Stars
    star
    7,821
  • Rank 4,849 (Top 0.1 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

State so simple, it goes without saying





Unstated Logo







Unstated

State so simple, it goes without saying

๐Ÿ‘‹ Check out the *-next version of Unstated with an all new React Hooks API โ†’

Installation

yarn add unstated

Example

// @flow
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')
);

For more examples, see the example/ directory.

Happy Customers

"Unstated is a breath of fresh air for state management. I rewrote my whole app to use it yesterday."

Sindre Sorhus

"When people say you don't need Redux most of the time, they actually mean you do need Unstated.
It's like setState on fucking horse steroids"

Ken Wheeler (obviously)

Guide

If you're like me, you're sick of all the ceremony around state management in React, you want something that fits in well with the React way of thinking, but doesn't command some crazy architecture and methodology.

So first off: Component state is nice! It makes sense and people can pick it up quickly:

class Counter extends React.Component {
  state = { count: 0 };
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };
  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  };
  render() {
    return (
      <div>
        <span>{this.state.count}</span>
        <button onClick={this.decrement}>-</button>
        <button onClick={this.increment}>+</button>
      </div>
    );
  }
}

As a new React developer you might not know exactly how everything works, but you can get a general sense pretty quickly.

The only problem here is that we can't easily share this state with other components in our tree. Which is intentional! React components are designed to be very self-contained.

What would be great is if we could replicate the nice parts of React's component state API while sharing it across multiple components.

But how do we share values between components in React? Through "context".

Note: The following is part of the new React.createContext API described in this RFC.

const Amount = React.createContext(1);

class Counter extends React.Component {
  state = { count: 0 };
  increment = amount => { this.setState({ count: this.state.count + amount }); };
  decrement = amount => { this.setState({ count: this.state.count - amount }); };
  render() {
    return (
      <Amount.Consumer>
        {amount => (
          <div>
            <span>{this.state.count}</span>
            <button onClick={() => this.decrement(amount)}>-</button>
            <button onClick={() => this.increment(amount)}>+</button>
          </div>
        )}
      </Amount.Consumer>
    );
  }
}

class AmountAdjuster extends React.Component {
  state = { amount: 0 };
  handleChange = event => {
    this.setState({
      amount: parseInt(event.currentTarget.value, 10)
    });
  };
  render() {
    return (
      <Amount.Provider value={this.state.amount}>
        <div>
          {this.props.children}
          <input type="number" value={this.state.amount} onChange={this.handleChange}/>
        </div>
      </Amount.Provider>
    );
  }
}

render(
  <AmountAdjuster>
    <Counter/>
  </AmountAdjuster>
);

This is already pretty great. Once you get a little bit used to React's way of thinking, it makes total sense and it's very predictable.

But can we build on this pattern to make something even nicer?

Introducing Unstated

Well this is where Unstated comes in.

Unstated is designed to build on top of the patterns already set out by React components and context.

It has three pieces:

Container

We're going to want another place to store our state and some of the logic for updating it.

Container is a very simple class which is meant to look just like React.Component but with only the state-related bits: this.state and this.setState.

class CounterContainer extends Container {
  state = { count: 0 };
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };
  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  };
}

Behind the scenes our Containers are also event emitters that our app can subscribe to for updates. When you call setState it triggers components to re-render, be careful not to mutate this.state directly or your components won't re-render.

setState()

setState() in Container mimics React's setState() method as closely as possible.

class CounterContainer extends Container {
  state = { count: 0 };
  increment = () => {
    this.setState(
      state => {
        return { count: state.count + 1 };
      },
      () => {
        console.log('Updated!');
      }
    );
  };
}

It's also run asynchronously, so you need to follow the same rules as React.

Don't read state immediately after setting it

class CounterContainer extends Container {
  state = { count: 0 };
  increment = () => {
    this.setState({ count: 1 });
    console.log(this.state.count); // 0
  };
}

If you are using previous state to calculate the next state, use the function form

class CounterContainer extends Container {
  state = { count: 0 };
  increment = () => {
    this.setState(state => {
      return { count: state.count + 1 };
    });
  };
}

However, unlike React's setState() Unstated's setState() returns a promise, so you can await it like this:

class CounterContainer extends Container {
  state = { count: 0 };
  increment = async () => {
    await this.setState({ count: 1 });
    console.log(this.state.count); // 1
  };
}

Async functions are now available in all the major browsers, but you can also use Babel to compile them down to something that works in every browser.

<Subscribe>

Next we'll need a piece to introduce our state back into the tree so that:

  • When state changes, our components re-render.
  • We can depend on our container's state.
  • We can call methods on our container.

For this we have the <Subscribe> component which allows us to pass our container classes/instances and receive instances of them in the tree.

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

<Subscribe> will automatically construct our container and listen for changes.

<Provider>

The final piece that we'll need is something to store all of our instances internally. For this we have <Provider>.

render(
  <Provider>
    <Counter />
  </Provider>
);

We can do some interesting things with <Provider> as well like dependency injection:

let counter = new CounterContainer();

render(
  <Provider inject={[counter]}>
    <Counter />
  </Provider>
);

Testing

Whenever we consider the way that we write the state in our apps we should be thinking about testing.

We want to make sure that our state containers have a clean way

Well because our containers are very simple classes, we can construct them in tests and assert different things about them very easily.

test('counter', async () => {
  let counter = new CounterContainer();
  assert(counter.state.count === 0);

  await counter.increment();
  assert(counter.state.count === 1);

  await counter.decrement();
  assert(counter.state.count === 0);
});

If we want to test the relationship between our container and the component we can again construct our own instance and inject it into the tree.

test('counter', async () => {
  let counter = new CounterContainer();
  let tree = render(
    <Provider inject={[counter]}>
      <Counter />
    </Provider>
  );

  await click(tree, '#increment');
  assert(counter.state.count === 1);

  await click(tree, '#decrement');
  assert(counter.state.count === 0);
});

Dependency injection is useful in many ways. Like if we wanted to stub out a method in our state container we can do that painlessly.

test('counter', async () => {
  let counter = new CounterContainer();
  let inc = stub(counter, 'increment');
  let dec = stub(counter, 'decrement');

  let tree = render(
    <Provider inject={[counter]}>
      <Counter />
    </Provider>
  );

  await click(tree, '#increment');
  assert(inc.calls.length === 1);
  assert(dec.calls.length === 0);
});

We don't even have to do anything to clean up after ourselves because we just throw everything out afterwards.

FAQ

What state should I put into Unstated?

The React community has focused a lot on trying to put all their state in one place. You could keep doing that with Unstated, but I wouldn't recommend it.

I would recommend a multi-part solution.

First, use local component state as much as you possibly can. That counter example from above never should have been refactored away from component state, it was fine before Unstated.

Second, use libraries to abstract away the bits of state that you'll repeat over and over.

Like if form state has you down, you might want to use a library like Final Form.

If fetching data is getting to be too much, maybe try out Apollo. Or even something uncool but familiar and reliable like Backbone models and collections. What? Are you too cool to use an old framework?

Third, a lot of shared state between components is localized to a few components in the tree.

<Tabs>
  <Tab>One</Tab>
  <Tab>Two</Tab>
  <Tab>Three</Tab>
</Tabs>

For this, I recommend using React's built-in React.createContext() API and being careful in designing the API for the base components you create.

Note: If you're on an old version of React and want to use the new context API, I've got you

Finally, (and only after other things are exhausted), if you really need some global state to be shared throughout your app, you can use Unstated.

I know all of this might sound somehow more complicated, but it's a matter of using the right tool for the job and not forcing a single paradigm on the entire universe.

Unstated isn't ambitious, use it as you need it, it's nice and small for that reason. Don't think of it as a "Redux killer". Don't go trying to build complex tools on top of it. Don't reinvent the wheel. Just try it out and see how you like it.

Passing your own instances directly to <Subscribe to>

If you want to use your own instance of a container directly to <Subscribe> and you don't care about dependency injection, you can do so:

let counter = new CounterContainer();

function Counter() {
  return (
    <Subscribe to={[counter]}>
      {counter => <div>...</div>}
    </Subscribe>
  );
}

You just need to keep a couple things in mind:

  1. You are opting out of dependency injection, you won't be able to <Provider inject> another instance in your tests.
  2. Your instance will be local to whatever <Subscribe>'s you pass it to, you will end up with multiple instances of your container if you don't pass the same reference in everywhere.

Also remember that it is okay to use <Provider inject> in your application code, you can pass your instance in there. It's probably better to do that in most scenarios anyways (cause then you get dependency injection and all that good stuff).

How can I pass in options to my container?

A good pattern for doing this might be to add a constructor to your container which accepts props sorta like React components. Then create your own instance of your container and pass it into <Provider inject>.

class CounterContainer extends Container {
  constructor(props = {}) {
    super();
    this.state = {
      amount: props.initialAmount || 1,
      count: 0
    };
  }

  increment = () => {
    this.setState({ count: this.state.count + this.state.amount });
  };
}

let counter = new CounterContainer({
  initialAmount: 5
});

render(
  <Provider inject={[counter]}>
    <Counter />
  </Provider>
);

Related

More Repositories

1

the-super-tiny-compiler

โ›„ Possibly the smallest compiler ever
JavaScript
25,786
star
2

react-loadable

โณ A higher order component for loading components with promises.
JavaScript
16,596
star
3

babel-handbook

๐Ÿ“˜ A guided handbook on how to use Babel and how to create plugins for Babel.
11,988
star
4

itsy-bitsy-data-structures

๐Ÿฐ All the things you didn't know you wanted to know about data structures
JavaScript
8,600
star
5

spectacle-code-slide

๐Ÿค˜ Present code with style
JavaScript
4,164
star
6

unstated-next

200 bytes to never think about React state management libraries ever again
TypeScript
4,092
star
7

tinykeys

A tiny (~400 B) & modern library for keybindings.
HTML
3,362
star
8

babel-react-optimize

๐Ÿš€ A Babel preset and plugins for optimizing React code.
JavaScript
1,677
star
9

tailwindcss-animate

A Tailwind CSS plugin for creating beautiful animations
JavaScript
1,084
star
10

glow

Make your Flow errors GLOW
JavaScript
699
star
11

create-react-context

Polyfill for the proposed React context API
JavaScript
695
star
12

json-parser-in-typescript-very-bad-idea-please-dont-use

JSON Parser written entirely in TypeScript's type system
TypeScript
424
star
13

react-gridlist

A virtual-scrolling GridList component based on CSS Grids
TypeScript
421
star
14

favorite-software

๐ŸŒŸ Best software for developers and power users.
355
star
15

marionette-wires

:shipit: An opinionated example application built with Marionette.js.
JavaScript
325
star
16

pretty-format

โœจ Stringify any JavaScript value
304
star
17

ghost-lang

๐Ÿ‘ป A friendly little language for you and me.
300
star
18

documentation-handbook

How to write high-quality friendly documentation that people want to read.
268
star
19

roast-my-deps

Your dependencies are bad and you should feel bad
JavaScript
265
star
20

bey

Simple immutable state for React using Immer
JavaScript
260
star
21

tickedoff

Tiny library (<200B gzip) for deferring something by a "tick"
JavaScript
217
star
22

react-jeff

A Good Form Library
TypeScript
213
star
23

react-performance-observer

Get performance measurements from React Fiber
JavaScript
210
star
24

gender-regex

Regex to test for valid genders
JavaScript
193
star
25

anti-fascist-mit-license

MIT license with additional text to prohibit use by fascists
187
star
26

purposefile

Make sure every file in your repo is exactly where it should be
TypeScript
168
star
27

react-loadable-example

Example project for React Loadable
JavaScript
149
star
28

bootcamp

๐Ÿ‘ข Jasmine-style BDD testing written in Sass for Sass.
CSS
141
star
29

write-files-atomic

Write many files atomically
JavaScript
124
star
30

sarcastic

Cast unknown values to typed values
JavaScript
98
star
31

ninos

Simple stubbing/spying for AVA
JavaScript
96
star
32

repo-growth

Measure how fast your repo is growing using cloc
JavaScript
89
star
33

workspaces-run

Run tasks/scripts across Yarn/Lerna/Bolt/etc workspaces.
TypeScript
88
star
34

license

The MIT license (with personal exceptions)
86
star
35

scritch

A small CLI to help you write sharable scripts for your team
JavaScript
84
star
36

react-markers

Add markers to your React components for easy testing with actual DOM elements
JavaScript
80
star
37

assert-equal-jsx

assertEqualJSX
JavaScript
78
star
38

proposal-promise-prototype-inspect

Proposal for Promise.prototype.inspect
JavaScript
78
star
39

globby-cli

User-friendly glob matching CLI
JavaScript
76
star
40

spawndamnit

Take care of your spawn()
JavaScript
76
star
41

grob

grep, but in JavaScript... I've truly outdone myself.
JavaScript
72
star
42

react-required-if

React PropType to conditionally add `.isRequired` based on other props
JavaScript
71
star
43

havetheybeenpwned

Test if your user's password has been pwned using the haveibeenpwned.com API
JavaScript
69
star
44

react-prop-matrix

Render something using every possible combination of props
JavaScript
68
star
45

renderator

JavaScript
65
star
46

dark-mode-github-readme-logos

How to make logos in your README that support GitHub's new dark mode
64
star
47

reduxxx

Redux, explicit.
TypeScript
64
star
48

babel-plugin-react-pure-components

Optimize React code by making pure classes into functions
JavaScript
61
star
49

react-test-renderer

[DEPRECATED] A lightweight solution to testing fully-rendered React Components
JavaScript
58
star
50

fixturez

Easily create and maintain test fixtures in the file system
JavaScript
58
star
51

ballistic

๐Ÿ”จ Utility-Belt Library for Sass
CSS
56
star
52

enable-npm-2fa

A script for enabling 2FA on all of your npm packages
JavaScript
55
star
53

cirbuf

A tiny and fast circular buffer
TypeScript
53
star
54

VisibilityObserver

Experimental API for observing the visible box of an element
TypeScript
51
star
55

dependency-free

An experiment to unify/speed up CI/local development via small Docker containers
TypeScript
49
star
56

react-stylish

๐ŸŽ€ Make your React component style-able by all
JavaScript
47
star
57

naw

Your very own containerized build system!
TypeScript
47
star
58

tested-components

Browser integration testing utils for styled-components
JavaScript
41
star
59

jamie.build

the website
HTML
41
star
60

codeowners-enforcer

Enforce CODEOWNERS files on your repo
Rust
41
star
61

std-pkg

The Official package.json Standardโ„ข for Npmยฎ endorsed fields
JavaScript
41
star
62

babel-plugin-private-underscores

Make _classMembers 'private' using symbols
JavaScript
39
star
63

userscript-github-disable-turbolinks

A userscript to disable GitHub turbolinks to force full page navigations
JavaScript
39
star
64

git-workflow

Git workflow for teams
38
star
65

pride

๐Ÿ‘ฌ PrideJS logo
38
star
66

babel-plugin-import-inspector

Babel plugin to report dynamic imports with import-inspector with metadata about the import
JavaScript
38
star
67

revalid

Composable validators
JavaScript
37
star
68

ci-parallel-vars

Get CI environment variables for parallelizing builds
JavaScript
37
star
69

crowdin-sync

๐ŸŒ How to setup Crowdin to sync with GitHub
Ruby
37
star
70

incremental-dom-react-helper

Helper to make Google's incremental-dom library work with React's compile target today.
JavaScript
36
star
71

guarded-string

Prevent accidentally introducing XSS holes with the strings in your app
JavaScript
36
star
72

babel-plugin-hash-strings

Replace all instances of "@@strings like this" with hashes.
JavaScript
35
star
73

react-module-experiment

JavaScript
34
star
74

task-graph-runner

Run async tasks with dependencies
JavaScript
34
star
75

json-peek

Stringify JSON *just enough* to see what it is
JavaScript
33
star
76

babel-plugin-ken-wheeler

Code like you dope
JavaScript
33
star
77

how-to-build-a-compiler

How to build a compiler โ€“ย THE TALK
HTML
33
star
78

js-memory-heap-profiling

JavaScript
32
star
79

backbone.service

A simple service class for Backbone.
JavaScript
31
star
80

dep-size-inspect

JavaScript
29
star
81

pffffff

pfffffffffffffffffffff whatever
JavaScript
28
star
82

shimiteer

Puppeteer API shim for other browsers using WebdriverIO
JavaScript
27
star
83

better-directory-sort

Improved sorting order for directory entities
JavaScript
27
star
84

isolated-core-demo

JavaScript
27
star
85

graph-sequencer

Sort items in a graph using a topological sort while resolving cycles with priority groups
JavaScript
27
star
86

import-inspector

Wrap dynamic imports with metadata about the import
JavaScript
26
star
87

backbone-routing

Simple router and route classes for Backbone.
JavaScript
26
star
88

flow-shut-up

Add inline Flow comments to make Flow shut up about errors
JavaScript
25
star
89

tumblr-downloader

Download all your female-presenting nipples from Tumblr
JavaScript
22
star
90

proposal-promise-settle

This repository is a work in progress and not seeking feedback yet.
JavaScript
22
star
91

backbone.storage

A simple storage class for Backbone Models and Collections.
JavaScript
22
star
92

parcel-rust-example

Example of using Rust code in Parcel
HTML
22
star
93

temperment

Get a random temporary file or directory path that will delete itself
JavaScript
22
star
94

is-mergeable

Check if a GitHub Pull Request is in a (most likely) mergeable state
JavaScript
22
star
95

gud

Create a 'gud nuff' (not cryptographically secure) globally unique id
JavaScript
21
star
96

min-indent

Get the shortest leading whitespace from lines in a string
JavaScript
20
star
97

babel-setup-react-transform

Example Babel project using babel-plugin-react-transform
JavaScript
20
star
98

codeowners-utils

Utilities for working with CODEOWNERS files
TypeScript
19
star
99

my-react

Ideas for React APIs
JavaScript
18
star
100

LibManUal

Shell
18
star