• Stars
    star
    4,092
  • Rank 10,113 (Top 0.3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated 12 months ago

Reviews

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

Repository Details

200 bytes to never think about React state management libraries ever again

English | 中文 | Русский | ภาษาไทย | Tiếng Việt
(Please contribute translations!)

Unstated Next

200 bytes to never think about React state management libraries ever again

  • React Hooks use them for all your state management.
  • ~200 bytes min+gz.
  • Familiar API just use React as intended.
  • Minimal API it takes 5 minutes to learn.
  • Written in TypeScript and will make it easier for you to type your React code.

But, the most important question: Is this better than Redux? Well...

  • It's smaller. It's 40x smaller.
  • It's faster. Componentize the problem of performance.
  • It's easier to learn. You already will have to know React Hooks & Context, just use them, they rock.
  • It's easier to integrate. Integrate one component at a time, and easily integrate with every React library.
  • It's easier to test. Testing reducers is a waste of your time, make it easier to test your React components.
  • It's easier to typecheck. Designed to make most of your types inferable.
  • It's minimal. It's just React.

So you decide.

See Migration From Unstated docs →

Install

npm install --save unstated-next

Example

import React, { useState } from "react"
import { createContainer } from "unstated-next"
import { render } from "react-dom"

function useCounter(initialState = 0) {
  let [count, setCount] = useState(initialState)
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  return { count, decrement, increment }
}

let Counter = createContainer(useCounter)

function CounterDisplay() {
  let counter = Counter.useContainer()
  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <span>{counter.count}</span>
      <button onClick={counter.increment}>+</button>
    </div>
  )
}

function App() {
  return (
    <Counter.Provider>
      <CounterDisplay />
      <Counter.Provider initialState={2}>
        <div>
          <div>
            <CounterDisplay />
          </div>
        </div>
      </Counter.Provider>
    </Counter.Provider>
  )
}

render(<App />, document.getElementById("root"))

API

createContainer(useHook)

import { createContainer } from "unstated-next"

function useCustomHook() {
  let [value, setValue] = useState()
  let onChange = e => setValue(e.currentTarget.value)
  return { value, onChange }
}

let Container = createContainer(useCustomHook)
// Container === { Provider, useContainer }

<Container.Provider>

function ParentComponent() {
  return (
    <Container.Provider>
      <ChildComponent />
    </Container.Provider>
  )
}

<Container.Provider initialState>

function useCustomHook(initialState = "") {
  let [value, setValue] = useState(initialState)
  // ...
}

function ParentComponent() {
  return (
    <Container.Provider initialState={"value"}>
      <ChildComponent />
    </Container.Provider>
  )
}

Container.useContainer()

function ChildComponent() {
  let input = Container.useContainer()
  return <input value={input.value} onChange={input.onChange} />
}

useContainer(Container)

import { useContainer } from "unstated-next"

function ChildComponent() {
  let input = useContainer(Container)
  return <input value={input.value} onChange={input.onChange} />
}

Guide

If you've never used React Hooks before, I recommend pausing and going to read through the excellent docs on the React site.

So with hooks you might create a component like this:

function CounterDisplay() {
  let [count, setCount] = useState(0)
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  return (
    <div>
      <button onClick={decrement}>-</button>
      <p>You clicked {count} times</p>
      <button onClick={increment}>+</button>
    </div>
  )
}

Then if you want to share the logic behind the component, you could pull it out into a custom hook:

function useCounter() {
  let [count, setCount] = useState(0)
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  return { count, decrement, increment }
}

function CounterDisplay() {
  let counter = useCounter()
  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
    </div>
  )
}

But what if you want to share the state in addition to the logic, what do you do?

This is where context comes into play:

function useCounter() {
  let [count, setCount] = useState(0)
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  return { count, decrement, increment }
}

let Counter = createContext(null)

function CounterDisplay() {
  let counter = useContext(Counter)
  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
    </div>
  )
}

function App() {
  let counter = useCounter()
  return (
    <Counter.Provider value={counter}>
      <CounterDisplay />
      <CounterDisplay />
    </Counter.Provider>
  )
}

This is great, it's perfect, more people should write code like this.

But sometimes we all need a little bit more structure and intentional API design in order to get it consistently right.

By introducing the createContainer() function, you can think about your custom hooks as "containers" and have an API that's clear and prevents you from using it wrong.

import { createContainer } from "unstated-next"

function useCounter() {
  let [count, setCount] = useState(0)
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  return { count, decrement, increment }
}

let Counter = createContainer(useCounter)

function CounterDisplay() {
  let counter = Counter.useContainer()
  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
    </div>
  )
}

function App() {
  return (
    <Counter.Provider>
      <CounterDisplay />
      <CounterDisplay />
    </Counter.Provider>
  )
}

Here's the diff of that change:

- import { createContext, useContext } from "react"
+ import { createContainer } from "unstated-next"

  function useCounter() {
    ...
  }

- let Counter = createContext(null)
+ let Counter = createContainer(useCounter)

  function CounterDisplay() {
-   let counter = useContext(Counter)
+   let counter = Counter.useContainer()
    return (
      <div>
        ...
      </div>
    )
  }

  function App() {
-   let counter = useCounter()
    return (
-     <Counter.Provider value={counter}>
+     <Counter.Provider>
        <CounterDisplay />
        <CounterDisplay />
      </Counter.Provider>
    )
  }

If you're using TypeScript (which I encourage you to learn more about if you are not), this also has the benefit of making TypeScript's built-in inference work better. As long as your custom hook is typed, then everything else will just work.

Tips

Tip #1: Composing Containers

Because we're just working with custom React hooks, we can compose containers inside of other hooks.

function useCounter() {
  let [count, setCount] = useState(0)
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  return { count, decrement, increment, setCount }
}

let Counter = createContainer(useCounter)

function useResettableCounter() {
  let counter = Counter.useContainer()
  let reset = () => counter.setCount(0)
  return { ...counter, reset }
}

Tip #2: Keeping Containers Small

This can be useful for keeping your containers small and focused. Which can be important if you want to code split the logic in your containers: Just move them to their own hooks and keep just the state in containers.

function useCount() {
  return useState(0)
}

let Count = createContainer(useCount)

function useCounter() {
  let [count, setCount] = Count.useContainer()
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  let reset = () => setCount(0)
  return { count, decrement, increment, reset }
}

Tip #3: Optimizing components

There's no "optimizing" unstated-next to be done, all of the optimizations you might do would be standard React optimizations.

1) Optimizing expensive sub-trees by splitting the component apart

Before:

function CounterDisplay() {
  let counter = Counter.useContainer()
  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
      <div>
        <div>
          <div>
            <div>SUPER EXPENSIVE RENDERING STUFF</div>
          </div>
        </div>
      </div>
    </div>
  )
}

After:

function ExpensiveComponent() {
  return (
    <div>
      <div>
        <div>
          <div>SUPER EXPENSIVE RENDERING STUFF</div>
        </div>
      </div>
    </div>
  )
}

function CounterDisplay() {
  let counter = Counter.useContainer()
  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
      <ExpensiveComponent />
    </div>
  )
}

2) Optimizing expensive operations with useMemo()

Before:

function CounterDisplay(props) {
  let counter = Counter.useContainer()

  // Recalculating this every time `counter` changes is expensive
  let expensiveValue = expensiveComputation(props.input)

  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
    </div>
  )
}

After:

function CounterDisplay(props) {
  let counter = Counter.useContainer()

  // Only recalculate this value when its inputs have changed
  let expensiveValue = useMemo(() => {
    return expensiveComputation(props.input)
  }, [props.input])

  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
    </div>
  )
}

3) Reducing re-renders using React.memo() and useCallback()

Before:

function useCounter() {
  let [count, setCount] = useState(0)
  let decrement = () => setCount(count - 1)
  let increment = () => setCount(count + 1)
  return { count, decrement, increment }
}

let Counter = createContainer(useCounter)

function CounterDisplay(props) {
  let counter = Counter.useContainer()
  return (
    <div>
      <button onClick={counter.decrement}>-</button>
      <p>You clicked {counter.count} times</p>
      <button onClick={counter.increment}>+</button>
    </div>
  )
}

After:

function useCounter() {
  let [count, setCount] = useState(0)
  let decrement = useCallback(() => setCount(count - 1), [count])
  let increment = useCallback(() => setCount(count + 1), [count])
  return { count, decrement, increment }
}

let Counter = createContainer(useCounter)

let CounterDisplayInner = React.memo(props => {
  return (
    <div>
      <button onClick={props.decrement}>-</button>
      <p>You clicked {props.count} times</p>
      <button onClick={props.increment}>+</button>
    </div>
  )
})

function CounterDisplay(props) {
  let counter = Counter.useContainer()
  return <CounterDisplayInner {...counter} />
}

4) Wrapping your elements with useMemo()

via Dan Abramov

Before:

function CounterDisplay(props) {
  let counter = Counter.useContainer()
  let count = counter.count
  
  return (
    <p>You clicked {count} times</p>
  )
}

After:

function CounterDisplay(props) {
  let counter = Counter.useContainer()
  let count = counter.count
  
  return useMemo(() => (
    <p>You clicked {count} times</p>
  ), [count])
}

Relation to Unstated

I consider this library the spiritual successor to Unstated. I created Unstated because I believed that React was really great at state management already and the only missing piece was sharing state and logic easily. So I created Unstated to be the "minimal" solution to sharing React state and logic.

However, with Hooks, React has become much better at sharing state and logic. To the point that I think Unstated has become an unnecessary abstraction.

HOWEVER, I think many developers have struggled seeing how to share state and logic with React Hooks for "application state". That may just be an issue of documentation and community momentum, but I think that an API could help bridge that mental gap.

That API is what Unstated Next is. Instead of being the "Minimal API for sharing state and logic in React", it is now the "Minimal API for understanding shared state and logic in React".

I've always been on the side of React. I want React to win. I would like to see the community abandon state management libraries like Redux, and find better ways of making use of React's built-in toolchain.

If instead of using Unstated, you just want to use React itself, I would highly encourage that. Write blog posts about it! Give talks about it! Spread your knowledge in the community.

Migration from unstated

I've intentionally published this as a separate package name because it is a complete reset on the API. This way you can have both installed and migrate incrementally.

Please provide me with feedback on that migration process, because over the next few months I hope to take that feedback and do two things:

  • Make sure unstated-next fulfills all the needs of unstated users.
  • Make sure unstated has a clean migration process towards unstated-next.

I may choose to add APIs to either library to make life easier for developers. For unstated-next I promise that the added APIs will be as minimal as possible and I'll try to keep the library small.

In the future, I will likely merge unstated-next back into unstated as a new major version. unstated-next will still exist so that you can have both unstated@2 and unstated-next installed. Then when you are done with the migration, you can update to unstated@3 and remove unstated-next (being sure to update all your imports as you do... should be just a find-and-replace).

Even though this is a major new API change, I hope that I can make this migration as easy as possible on you. I'm optimizing for you to get to using the latest React Hooks APIs and not for preserving code written with Unstated.Container's. Feel free to provide feedback on how that could be done better.

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,881
star
4

itsy-bitsy-data-structures

🏰 All the things you didn't know you wanted to know about data structures
JavaScript
8,574
star
5

unstated

State so simple, it goes without saying
JavaScript
7,821
star
6

spectacle-code-slide

🤘 Present code with style
JavaScript
4,170
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,680
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

naw

Your very own containerized build system!
TypeScript
47
star
57

react-stylish

🎀 Make your React component style-able by all
JavaScript
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

proposal-promise-settle

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

tumblr-downloader

Download all your female-presenting nipples from Tumblr
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