unstated-next
200 bytes to never think about React state management libraries ever again
Top Related Projects
Official React bindings for Redux
Lightweight React bindings for MobX based on React 16.8 and Hooks
🐻 Bear necessities for state management in React
React Context + State
React useContextSelector hook in userland
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Quick Overview
Unstated-next is a lightweight state management library for React applications. It provides a simple and intuitive way to create and share state between components using React hooks and context, without the complexity of larger state management solutions like Redux.
Pros
- Simple and easy to learn, with a minimal API
- Leverages React's built-in hooks and context for efficient state management
- Lightweight and has no dependencies
- Encourages modular and reusable state containers
Cons
- May not be suitable for large-scale applications with complex state requirements
- Limited built-in features compared to more comprehensive state management libraries
- Requires React version 16.8 or higher (due to hooks usage)
- Less ecosystem support and tooling compared to more established libraries like Redux
Code Examples
Creating a counter container:
import { createContainer } from 'unstated-next'
import { useState } from 'react'
function useCounter() {
const [count, setCount] = useState(0)
const increment = () => setCount(count + 1)
const decrement = () => setCount(count - 1)
return { count, increment, decrement }
}
const Counter = createContainer(useCounter)
Using the counter in a component:
function CounterDisplay() {
const counter = Counter.useContainer()
return (
<div>
<p>Count: {counter.count}</p>
<button onClick={counter.increment}>+</button>
<button onClick={counter.decrement}>-</button>
</div>
)
}
Providing the container to the app:
function App() {
return (
<Counter.Provider>
<CounterDisplay />
</Counter.Provider>
)
}
Getting Started
-
Install unstated-next:
npm install unstated-next
-
Create a container:
import { createContainer } from 'unstated-next' import { useState } from 'react' function useCustomHook() { const [state, setState] = useState(initialState) // Add your state logic here return { state, setState } } export const CustomContainer = createContainer(useCustomHook)
-
Use the container in your components:
import { CustomContainer } from './customContainer' function MyComponent() { const { state, setState } = CustomContainer.useContainer() // Use state and setState in your component }
-
Wrap your app with the provider:
import { CustomContainer } from './customContainer' function App() { return ( <CustomContainer.Provider> <MyComponent /> </CustomContainer.Provider> ) }
Competitor Comparisons
Official React bindings for Redux
Pros of react-redux
- More robust and feature-rich for complex state management
- Extensive ecosystem with middleware and developer tools
- Better suited for large-scale applications with complex data flows
Cons of react-redux
- Steeper learning curve and more boilerplate code
- Can be overkill for smaller applications or simpler state management needs
- Requires additional setup and configuration
Code Comparison
react-redux:
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const store = createStore(rootReducer);
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
unstated-next:
import { createContainer } from 'unstated-next';
const CounterContainer = createContainer(useCounter);
function App() {
return (
<CounterContainer.Provider>
<Counter />
</CounterContainer.Provider>
);
}
Summary
react-redux is a more powerful and comprehensive state management solution, ideal for larger applications with complex state requirements. It offers a rich ecosystem and robust tooling but comes with a steeper learning curve and more setup overhead.
unstated-next, on the other hand, provides a simpler and more lightweight approach to state management. It's easier to learn and implement, making it suitable for smaller projects or when you need a quick state management solution without the complexity of Redux.
The choice between the two depends on the specific needs of your project, its scale, and the complexity of your state management requirements.
Lightweight React bindings for MobX based on React 16.8 and Hooks
Pros of mobx-react-lite
- More powerful and flexible state management solution
- Supports complex state structures and derived values
- Better performance for large-scale applications
Cons of mobx-react-lite
- Steeper learning curve due to more concepts and APIs
- Requires more boilerplate code
- Can be overkill for simple applications
Code Comparison
unstated-next:
const Counter = createContainer(() => {
const [count, setCount] = useState(0);
return { count, setCount };
});
function CounterDisplay() {
const counter = Counter.useContainer();
return <div>{counter.count}</div>;
}
mobx-react-lite:
const CounterStore = observable({
count: 0,
increment() { this.count++ },
});
const CounterDisplay = observer(() => {
return <div>{CounterStore.count}</div>;
});
Both libraries aim to simplify state management in React applications, but they take different approaches. unstated-next focuses on simplicity and leverages React's built-in hooks, making it easier to learn and use for developers already familiar with React. On the other hand, mobx-react-lite offers a more robust solution with additional features like computed values and actions, making it suitable for more complex state management scenarios. The choice between the two depends on the specific needs of your project and your team's familiarity with the concepts involved.
🐻 Bear necessities for state management in React
Pros of Zustand
- More lightweight and minimalistic approach to state management
- Supports middleware and devtools out of the box
- Can be used outside of React, making it more versatile
Cons of Zustand
- Less opinionated structure, which may lead to inconsistent patterns in larger projects
- Steeper learning curve for developers familiar with React's built-in state management
Code Comparison
Unstated-next:
const CounterContainer = createContainer(() => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return { count, increment };
});
function Counter() {
const counter = CounterContainer.useContainer();
return <button onClick={counter.increment}>{counter.count}</button>;
}
Zustand:
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}));
function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>{count}</button>;
}
Both libraries aim to simplify state management in React applications, but they take different approaches. Unstated-next focuses on using React's built-in hooks and context, while Zustand provides a more flexible and standalone solution. The choice between them depends on project requirements and developer preferences.
React Context + State
Pros of constate
- Supports TypeScript out of the box, providing better type safety
- Offers more flexibility with multiple contexts and selectors
- Allows for easier testing of state logic separately from components
Cons of constate
- Slightly more complex API compared to unstated-next
- May have a steeper learning curve for beginners
- Less popular and potentially less community support
Code Comparison
unstated-next:
const Counter = createContainer(() => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return { count, increment };
});
function CounterDisplay() {
const counter = Counter.useContainer();
return <div>{counter.count}</div>;
}
constate:
const useCounter = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return { count, increment };
};
const [CounterProvider, useCounterContext] = constate(useCounter);
function CounterDisplay() {
const { count } = useCounterContext();
return <div>{count}</div>;
}
Both libraries aim to simplify React state management, but constate offers more advanced features at the cost of slightly increased complexity. unstated-next provides a simpler API that may be more suitable for smaller projects or beginners. The choice between the two depends on the specific needs of your project and your team's familiarity with React state management patterns.
React useContextSelector hook in userland
Pros of use-context-selector
- Offers fine-grained control over re-renders by allowing selection of specific context values
- Potentially better performance in large applications with complex state structures
- Provides a more flexible API for consuming context values
Cons of use-context-selector
- Slightly more complex API compared to unstated-next's simpler approach
- Requires additional setup and configuration for optimal usage
- May introduce unnecessary complexity for smaller applications or simpler state management needs
Code Comparison
use-context-selector:
const MyComponent = () => {
const value = useContextSelector(MyContext, state => state.specificValue);
return <div>{value}</div>;
};
unstated-next:
const MyComponent = () => {
const { specificValue } = useContainer(MyContainer);
return <div>{specificValue}</div>;
};
Both libraries aim to improve React's context API and state management, but they take different approaches. use-context-selector focuses on optimizing performance through selective re-renders, while unstated-next provides a simpler, more straightforward API for managing and accessing state. The choice between the two depends on the specific needs of your project, with use-context-selector being more suitable for larger, performance-critical applications, and unstated-next offering a more accessible solution for general use cases.
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Pros of Recoil
- More powerful and flexible state management, supporting derived state and asynchronous queries
- Better performance optimization for large-scale applications with fine-grained updates
- Built-in support for time-travel debugging and persistence
Cons of Recoil
- Steeper learning curve due to more complex API and concepts
- Requires more boilerplate code for setup and state definitions
- Still in experimental phase, which may lead to API changes and potential instability
Code Comparison
Unstated-next:
const Counter = createContainer(() => {
const [count, setCount] = useState(0);
return { count, setCount };
});
function CounterDisplay() {
const counter = Counter.useContainer();
return <div>{counter.count}</div>;
}
Recoil:
const counterState = atom({
key: 'counterState',
default: 0,
});
function CounterDisplay() {
const [count, setCount] = useRecoilState(counterState);
return <div>{count}</div>;
}
Both libraries aim to simplify state management in React applications, but Recoil offers more advanced features at the cost of increased complexity. Unstated-next provides a simpler API that closely resembles React's built-in hooks, making it easier to adopt for smaller projects. Recoil, on the other hand, is better suited for larger applications with complex state requirements and performance needs.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME

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()
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 ofunstated
users. - Make sure
unstated
has a clean migration process towardsunstated-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.
Top Related Projects
Official React bindings for Redux
Lightweight React bindings for MobX based on React 16.8 and Hooks
🐻 Bear necessities for state management in React
React Context + State
React useContextSelector hook in userland
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot