Convert Figma logo to code with AI

jamiebuilds logounstated

State so simple, it goes without saying

7,794
270
7,794
18

Top Related Projects

60,936

A JS library for predictable global state management

27,618

Simple, scalable state management.

48,653

🐻 Bear necessities for state management in React

Business logic with ease ☄️

Quick Overview

Unstated is a simple state management library for React that allows you to manage state without the need for complex state management solutions like Redux or MobX. It provides a lightweight and flexible way to manage state in your React applications.

Pros

  • Simplicity: Unstated is a lightweight and easy-to-use state management solution, making it a great choice for small to medium-sized React applications.
  • Flexibility: Unstated allows you to manage state in a way that fits your application's needs, without forcing you to adhere to a specific architecture.
  • Performance: Unstated uses React's built-in state management features, which are highly optimized for performance.
  • No Boilerplate: Unstated eliminates the need for boilerplate code that is often required by other state management libraries.

Cons

  • Limited Ecosystem: Unstated has a smaller ecosystem compared to more established state management solutions like Redux or MobX, which may limit the availability of third-party integrations and tooling.
  • Scaling Concerns: As your application grows in complexity, Unstated may not provide the same level of scalability and organization as more comprehensive state management solutions.
  • Learning Curve: While Unstated is relatively simple to use, developers who are more familiar with other state management libraries may need to adjust their mental model to work with Unstated.
  • Lack of Tooling: Unstated has a smaller ecosystem, which may mean fewer developer tools and integrations compared to other state management solutions.

Code Examples

Here are a few examples of how to use Unstated in your React application:

Creating a State Container

import { Subscribe, Container } from 'unstated';

class CounterContainer extends Container {
  state = {
    count: 0,
  };

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

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

Using the State Container in a Component

import { CounterContainer } from './CounterContainer';

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>
  );
}

Combining Multiple State Containers

import { Subscribe } from 'unstated';
import { CounterContainer } from './CounterContainer';
import { ThemeContainer } from './ThemeContainer';

function App() {
  return (
    <Subscribe to={[CounterContainer, ThemeContainer]}>
      {(counter, theme) => (
        <div className={theme.state.mode}>
          <Counter counter={counter} />
          <ThemeToggle theme={theme} />
        </div>
      )}
    </Subscribe>
  );
}

Getting Started

To get started with Unstated, you can follow these steps:

  1. Install the unstated package:
npm install unstated
  1. Create a state container:
import { Container } from 'unstated';

class CounterContainer extends Container {
  state = {
    count: 0,
  };

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

  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  };
}
  1. Use the state container in your React component:
import { Subscribe } from 'unstated';
import { CounterContainer } from './CounterContainer';

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

Competitor Comparisons

60,936

A JS library for predictable global state management

Pros of Redux

  • More mature and widely adopted ecosystem with extensive tooling and middleware
  • Centralized state management for complex applications
  • Time-travel debugging and predictable state updates

Cons of Redux

  • Steeper learning curve and more boilerplate code
  • Can be overkill for smaller applications
  • Requires careful consideration of immutability and reducer composition

Code Comparison

Redux:

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

Unstated:

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

Redux focuses on a centralized store with reducers, while Unstated uses React's built-in state management with a simplified API. Unstated requires less setup and boilerplate, making it easier to get started with, especially for smaller applications. However, Redux offers more powerful features for complex state management and debugging in larger applications.

27,618

Simple, scalable state management.

Pros of MobX

  • More powerful and feature-rich, offering advanced state management capabilities
  • Supports computed values and reactions, allowing for automatic updates based on state changes
  • Better performance for complex applications with large state trees

Cons of MobX

  • Steeper learning curve due to its more complex API and concepts
  • Requires decorators or configuration for optimal usage, which may not be ideal for all projects
  • Can lead to less explicit code, potentially making it harder to track state changes

Code Comparison

MobX:

import { makeObservable, observable, action } from "mobx";

class Store {
  constructor() {
    makeObservable(this, {
      count: observable,
      increment: action
    });
  }
  count = 0;
  increment = () => {
    this.count++;
  };
}

Unstated:

import { createContainer } from "unstated-next";

function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);
  return { count, increment };
}

const Counter = createContainer(useCounter);

MobX offers a more powerful state management solution with advanced features, but comes with a steeper learning curve. Unstated provides a simpler, more React-like approach to state management, making it easier to adopt for developers already familiar with React hooks.

48,653

🐻 Bear necessities for state management in React

Pros of zustand

  • Simpler API with less boilerplate code
  • Better TypeScript support out of the box
  • More flexible, allowing for middleware and custom store enhancers

Cons of zustand

  • Less opinionated, which may lead to inconsistent usage across a project
  • Lacks built-in React context integration, requiring additional setup for some use cases

Code Comparison

unstated:

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

function App() {
  return (
    <Provider>
      <Subscribe to={[Counter]}>
        {counter => <button onClick={counter.increment}>{counter.state.count}</button>}
      </Subscribe>
    </Provider>
  );
}

zustand:

const useStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 }))
}));

function App() {
  const { count, increment } = useStore();
  return <button onClick={increment}>{count}</button>;
}

Business logic with ease ☄️

Pros of effector

  • More powerful and flexible, supporting complex state management scenarios
  • Better TypeScript support with built-in type inference
  • Larger ecosystem with additional tools and integrations

Cons of effector

  • Steeper learning curve due to its more complex API
  • Potentially overkill for simple applications
  • Requires more boilerplate code for basic setups

Code Comparison

Unstated:

import { Container, Subscribe } from 'unstated';

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

const App = () => (
  <Subscribe to={[CounterContainer]}>
    {counter => <button onClick={counter.increment}>{counter.state.count}</button>}
  </Subscribe>
);

effector:

import { createStore, createEvent } from 'effector';
import { useStore } from 'effector-react';

const increment = createEvent();
const $count = createStore(0).on(increment, state => state + 1);

const App = () => {
  const count = useStore($count);
  return <button onClick={increment}>{count}</button>;
};

Both libraries aim to simplify state management in React applications, but effector offers more advanced features at the cost of increased complexity. Unstated provides a simpler API that may be sufficient for many projects, while effector is better suited for larger, more complex applications requiring fine-grained control over state and events.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README






Unstated Logo







Unstated

State so simple, it goes without saying

:wave: 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

NPM DownloadsLast 30 Days