Unstated Next

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

README

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.


Install


  1. ```sh
  2. npm install --save unstated-next
  3. ```

Example


  1. ``` js
  2. import React, { useState } from "react"
  3. import { createContainer } from "unstated-next"
  4. import { render } from "react-dom"

  5. function useCounter(initialState = 0) {
  6.   let [count, setCount] = useState(initialState)
  7.   let decrement = () => setCount(count - 1)
  8.   let increment = () => setCount(count + 1)
  9.   return { count, decrement, increment }
  10. }

  11. let Counter = createContainer(useCounter)

  12. function CounterDisplay() {
  13.   let counter = Counter.useContainer()
  14.   return (
  15.     <div>
  16.       <button onClick={counter.decrement}>-</button>
  17.       <span>{counter.count}</span>
  18.       <button onClick={counter.increment}>+</button>
  19.     </div>
  20.   )
  21. }

  22. function App() {
  23.   return (
  24.     <Counter.Provider>
  25.       <CounterDisplay />
  26.       <Counter.Provider initialState={2}>
  27.         <div>
  28.           <div>
  29.             <CounterDisplay />
  30.           </div>
  31.         </div>
  32.       </Counter.Provider>
  33.     </Counter.Provider>
  34.   )
  35. }

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

API


createContainer(useHook)


  1. ``` js
  2. import { createContainer } from "unstated-next"

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

  8. let Container = createContainer(useCustomHook)
  9. // Container === { Provider, useContainer }
  10. ```

### ``

  1. ``` js
  2. function ParentComponent() {
  3.   return (
  4.     <Container.Provider>
  5.       <ChildComponent />
  6.     </Container.Provider>
  7.   )
  8. }
  9. ```

### ``

  1. ``` js
  2. function useCustomHook(initialState = "") {
  3.   let [value, setValue] = useState(initialState)
  4.   // ...
  5. }

  6. function ParentComponent() {
  7.   return (
  8.     <Container.Provider initialState={"value"}>
  9.       <ChildComponent />
  10.     </Container.Provider>
  11.   )
  12. }
  13. ```

Container.useContainer()


  1. ``` js
  2. function ChildComponent() {
  3.   let input = Container.useContainer()
  4.   return <input value={input.value} onChange={input.onChange} />
  5. }
  6. ```

useContainer(Container)


  1. ``` js
  2. import { useContainer } from "unstated-next"

  3. function ChildComponent() {
  4.   let input = useContainer(Container)
  5.   return <input value={input.value} onChange={input.onChange} />
  6. }
  7. ```

Guide


If you've never used React Hooks before, I recommend pausing and going to read

So with hooks you might create a component like this:

  1. ``` js
  2. function CounterDisplay() {
  3.   let [count, setCount] = useState(0)
  4.   let decrement = () => setCount(count - 1)
  5.   let increment = () => setCount(count + 1)
  6.   return (
  7.     <div>
  8.       <button onClick={decrement}>-</button>
  9.       <p>You clicked {count} times</p>
  10.       <button onClick={increment}>+</button>
  11.     </div>
  12.   )
  13. }
  14. ```

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

  1. ``` js
  2. function useCounter() {
  3.   let [count, setCount] = useState(0)
  4.   let decrement = () => setCount(count - 1)
  5.   let increment = () => setCount(count + 1)
  6.   return { count, decrement, increment }
  7. }

  8. function CounterDisplay() {
  9.   let counter = useCounter()
  10.   return (
  11.     <div>
  12.       <button onClick={counter.decrement}>-</button>
  13.       <p>You clicked {counter.count} times</p>
  14.       <button onClick={counter.increment}>+</button>
  15.     </div>
  16.   )
  17. }
  18. ```

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:

  1. ``` js
  2. function useCounter() {
  3.   let [count, setCount] = useState(0)
  4.   let decrement = () => setCount(count - 1)
  5.   let increment = () => setCount(count + 1)
  6.   return { count, decrement, increment }
  7. }

  8. let Counter = createContext(null)

  9. function CounterDisplay() {
  10.   let counter = useContext(Counter)
  11.   return (
  12.     <div>
  13.       <button onClick={counter.decrement}>-</button>
  14.       <p>You clicked {counter.count} times</p>
  15.       <button onClick={counter.increment}>+</button>
  16.     </div>
  17.   )
  18. }

  19. function App() {
  20.   let counter = useCounter()
  21.   return (
  22.     <Counter.Provider value={counter}>
  23.       <CounterDisplay />
  24.       <CounterDisplay />
  25.     </Counter.Provider>
  26.   )
  27. }
  28. ```

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.

  1. ``` js
  2. import { createContainer } from "unstated-next"

  3. function useCounter() {
  4.   let [count, setCount] = useState(0)
  5.   let decrement = () => setCount(count - 1)
  6.   let increment = () => setCount(count + 1)
  7.   return { count, decrement, increment }
  8. }

  9. let Counter = createContainer(useCounter)

  10. function CounterDisplay() {
  11.   let counter = Counter.useContainer()
  12.   return (
  13.     <div>
  14.       <button onClick={counter.decrement}>-</button>
  15.       <p>You clicked {counter.count} times</p>
  16.       <button onClick={counter.increment}>+</button>
  17.     </div>
  18.   )
  19. }

  20. function App() {
  21.   return (
  22.     <Counter.Provider>
  23.       <CounterDisplay />
  24.       <CounterDisplay />
  25.     </Counter.Provider>
  26.   )
  27. }
  28. ```

Here's the diff of that change:

  1. ```diff
  2. - import { createContext, useContext } from "react"
  3. + import { createContainer } from "unstated-next"

  4.   function useCounter() {
  5.     ...
  6.   }

  7. - let Counter = createContext(null)
  8. + let Counter = createContainer(useCounter)

  9.   function CounterDisplay() {
  10. -   let counter = useContext(Counter)
  11. +   let counter = Counter.useContainer()
  12.     return (
  13.       <div>
  14.         ...
  15.       </div>
  16.     )
  17.   }

  18.   function App() {
  19. -   let counter = useCounter()
  20.     return (
  21. -     <Counter.Provider value={counter}>
  22. +     <Counter.Provider>
  23.         <CounterDisplay />
  24.         <CounterDisplay />
  25.       </Counter.Provider>
  26.     )
  27.   }
  28. ```

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.

  1. ``` js
  2. function useCounter() {
  3.   let [count, setCount] = useState(0)
  4.   let decrement = () => setCount(count - 1)
  5.   let increment = () => setCount(count + 1)
  6.   return { count, decrement, increment, setCount }
  7. }

  8. let Counter = createContainer(useCounter)

  9. function useResettableCounter() {
  10.   let counter = Counter.useContainer()
  11.   let reset = () => counter.setCount(0)
  12.   return { ...counter, reset }
  13. }
  14. ```

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.

  1. ``` js
  2. function useCount() {
  3.   return useState(0)
  4. }

  5. let Count = createContainer(useCount)

  6. function useCounter() {
  7.   let [count, setCount] = Count.useContainer()
  8.   let decrement = () => setCount(count - 1)
  9.   let increment = () => setCount(count + 1)
  10.   let reset = () => setCount(0)
  11.   return { count, decrement, increment, reset }
  12. }
  13. ```

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:

  1. ``` js
  2. function CounterDisplay() {
  3.   let counter = Counter.useContainer()
  4.   return (
  5.     <div>
  6.       <button onClick={counter.decrement}>-</button>
  7.       <p>You clicked {counter.count} times</p>
  8.       <button onClick={counter.increment}>+</button>
  9.       <div>
  10.         <div>
  11.           <div>
  12.             <div>SUPER EXPENSIVE RENDERING STUFF</div>
  13.           </div>
  14.         </div>
  15.       </div>
  16.     </div>
  17.   )
  18. }
  19. ```

After:

  1. ``` js
  2. function ExpensiveComponent() {
  3.   return (
  4.     <div>
  5.       <div>
  6.         <div>
  7.           <div>SUPER EXPENSIVE RENDERING STUFF</div>
  8.         </div>
  9.       </div>
  10.     </div>
  11.   )
  12. }

  13. function CounterDisplay() {
  14.   let counter = Counter.useContainer()
  15.   return (
  16.     <div>
  17.       <button onClick={counter.decrement}>-</button>
  18.       <p>You clicked {counter.count} times</p>
  19.       <button onClick={counter.increment}>+</button>
  20.       <ExpensiveComponent />
  21.     </div>
  22.   )
  23. }
  24. ```

2) Optimizing expensive operations with useMemo()


Before:

  1. ``` js
  2. function CounterDisplay(props) {
  3.   let counter = Counter.useContainer()

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

  6.   return (
  7.     <div>
  8.       <button onClick={counter.decrement}>-</button>
  9.       <p>You clicked {counter.count} times</p>
  10.       <button onClick={counter.increment}>+</button>
  11.     </div>
  12.   )
  13. }
  14. ```

After:

  1. ``` js
  2. function CounterDisplay(props) {
  3.   let counter = Counter.useContainer()

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

  8.   return (
  9.     <div>
  10.       <button onClick={counter.decrement}>-</button>
  11.       <p>You clicked {counter.count} times</p>
  12.       <button onClick={counter.increment}>+</button>
  13.     </div>
  14.   )
  15. }
  16. ```

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


Before:

  1. ``` js
  2. function useCounter() {
  3.   let [count, setCount] = useState(0)
  4.   let decrement = () => setCount(count - 1)
  5.   let increment = () => setCount(count + 1)
  6.   return { count, decrement, increment }
  7. }

  8. let Counter = createContainer(useCounter)

  9. function CounterDisplay(props) {
  10.   let counter = Counter.useContainer()
  11.   return (
  12.     <div>
  13.       <button onClick={counter.decrement}>-</button>
  14.       <p>You clicked {counter.count} times</p>
  15.       <button onClick={counter.increment}>+</button>
  16.     </div>
  17.   )
  18. }
  19. ```

After:

  1. ``` js
  2. function useCounter() {
  3.   let [count, setCount] = useState(0)
  4.   let decrement = useCallback(() => setCount(count - 1), [count])
  5.   let increment = useCallback(() => setCount(count + 1), [count])
  6.   return { count, decrement, increment }
  7. }

  8. let Counter = createContainer(useCounter)

  9. let CounterDisplayInner = React.memo(props => {
  10.   return (
  11.     <div>
  12.       <button onClick={props.decrement}>-</button>
  13.       <p>You clicked {props.count} times</p>
  14.       <button onClick={props.increment}>+</button>
  15.     </div>
  16.   )
  17. })

  18. function CounterDisplay(props) {
  19.   let counter = Counter.useContainer()
  20.   return <CounterDisplayInner {...counter} />
  21. }
  22. ```

4) Wrapping your elements with useMemo()



Before:

  1. ``` js
  2. function CounterDisplay(props) {
  3.   let counter = Counter.useContainer()
  4.   let count = counter.count
  5.   
  6.   return (
  7.     <p>You clicked {count} times</p>
  8.   )
  9. }
  10. ```

After:

  1. ``` js
  2. function CounterDisplay(props) {
  3.   let counter = Counter.useContainer()
  4.   let count = counter.count
  5.   
  6.   return useMemo(() => (
  7.     <p>You clicked {count} times</p>
  8.   ), [count])
  9. }
  10. ```

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.