Top Related Projects
Quick Overview
Unistore is a tiny centralized state container with component bindings for Preact and React. It provides a simple and lightweight solution for state management in JavaScript applications, offering an alternative to more complex state management libraries like Redux.
Pros
- Extremely lightweight (less than 1KB gzipped)
- Simple API with minimal boilerplate
- Compatible with both Preact and React
- Easy to learn and implement
Cons
- Limited features compared to more robust state management solutions
- May not be suitable for large-scale applications with complex state requirements
- Less community support and ecosystem compared to more popular alternatives
- Lack of built-in middleware support
Code Examples
- Creating a store:
import createStore from 'unistore'
const store = createStore({ count: 0 })
- Defining actions:
const actions = store => ({
increment: ({ count }) => ({ count: count + 1 }),
decrement: ({ count }) => ({ count: count - 1 })
})
- Connecting a component (React example):
import { connect } from 'unistore/react'
const Counter = ({ count, increment, decrement }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
)
export default connect('count', actions)(Counter)
Getting Started
To use Unistore in your project, follow these steps:
- Install Unistore:
npm install unistore
- Create a store and define actions:
import createStore from 'unistore'
const store = createStore({ count: 0 })
const actions = store => ({
increment: ({ count }) => ({ count: count + 1 }),
decrement: ({ count }) => ({ count: count - 1 })
})
- Connect your components (React example):
import { Provider, connect } from 'unistore/react'
const App = () => (
<Provider store={store}>
<ConnectedCounter />
</Provider>
)
const Counter = ({ count, increment, decrement }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
)
const ConnectedCounter = connect('count', actions)(Counter)
This setup provides a basic implementation of Unistore in a React application. Adjust the code as needed for your specific use case or if using Preact.
Competitor Comparisons
A JS library for predictable global state management
Pros of Redux
- More robust and feature-rich, suitable for complex state management
- Extensive ecosystem with middleware, dev tools, and community support
- Time-travel debugging and predictable state updates
Cons of Redux
- Steeper learning curve and more boilerplate code
- Potentially overkill for small to medium-sized applications
- Can lead to verbose code and increased complexity
Code Comparison
Redux:
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
};
Unistore:
const actions = store => ({
increment: ({ count }) => ({ count: count + 1 })
});
Redux requires more setup and boilerplate, while Unistore offers a simpler API with less code. Redux uses a switch statement in reducers, whereas Unistore uses action functions. Redux is more suitable for larger applications with complex state management needs, while Unistore is ideal for smaller projects or when simplicity is preferred.
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 and side effects
- Better suited for complex applications with intricate state dependencies
Cons of MobX
- Steeper learning curve due to its more complex API and concepts
- Potentially overkill for smaller applications or simpler state management needs
- Requires more boilerplate code and setup compared to Unistore
Code Comparison
MobX:
import { makeAutoObservable } from "mobx";
class Store {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment() {
this.count++;
}
}
Unistore:
import createStore from "unistore";
const store = createStore({ count: 0 });
const actions = store => ({
increment: ({ count }) => ({ count: count + 1 })
});
Summary
MobX is a more powerful and feature-rich state management solution, ideal for complex applications with intricate state dependencies. It offers advanced capabilities like computed values and reactions but comes with a steeper learning curve and more setup overhead. Unistore, on the other hand, provides a simpler and more lightweight approach to state management, making it better suited for smaller applications or projects with straightforward state needs. The choice between the two depends on the specific requirements and complexity of your application.
🐻 Bear necessities for state management in React
Pros of zustand
- More flexible and powerful, supporting middleware and async actions
- Better TypeScript support with less boilerplate
- Larger community and more frequent updates
Cons of zustand
- Slightly steeper learning curve due to more features
- Potentially overkill for very simple state management needs
Code Comparison
zustand:
import create from 'zustand'
const useStore = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
}))
unistore:
import createStore from 'unistore'
const store = createStore({ count: 0 })
const actions = store => ({
increment: ({ count }) => ({ count: count + 1 }),
})
Summary
zustand offers more advanced features and better TypeScript support, making it suitable for larger applications with complex state management needs. unistore, on the other hand, provides a simpler API that may be preferable for smaller projects or those requiring minimal state management. Both libraries aim to provide lightweight alternatives to more complex state management solutions, but zustand has gained more traction in the community and sees more frequent updates.
Business logic with ease ☄️
Pros of effector
- More powerful and flexible, supporting complex state management scenarios
- Better TypeScript support with strong typing
- Larger ecosystem with additional tools and integrations
Cons of effector
- Steeper learning curve due to more advanced concepts
- Potentially overkill for simple applications
- Larger bundle size compared to unistore
Code Comparison
effector:
import {createStore, createEvent} from 'effector'
const increment = createEvent()
const $counter = createStore(0)
.on(increment, state => state + 1)
$counter.watch(n => console.log('counter:', n))
increment()
unistore:
import createStore from 'unistore'
const store = createStore({ count: 0 })
const actions = store => ({
increment: ({ count }) => ({ count: count + 1 })
})
store.subscribe(state => console.log(state.count))
store.action(actions.increment)()
Both libraries provide state management solutions, but effector offers more advanced features and better TypeScript support. unistore is simpler and more lightweight, making it suitable for smaller projects. effector's approach is more declarative and scalable, while unistore follows a more traditional Redux-like pattern. Choose effector for complex applications with TypeScript, and unistore for simpler projects or when minimizing bundle size is crucial.
Actor-based state management & orchestration for complex app logic.
Pros of XState
- More powerful and expressive state management with finite state machines and statecharts
- Better suited for complex application logic and workflows
- Visualization tools for state machines, aiding in development and debugging
Cons of XState
- Steeper learning curve due to its more complex concepts
- Potentially overkill for simple applications with basic state management needs
- Larger bundle size compared to Unistore's minimal footprint
Code Comparison
XState:
import { createMachine, interpret } from 'xstate';
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: { on: { TOGGLE: 'active' } },
active: { on: { TOGGLE: 'inactive' } }
}
});
Unistore:
import createStore from 'unistore';
const store = createStore({ active: false });
const actions = store => ({
toggle: ({ active }) => ({ active: !active })
});
XState offers a more structured approach to state management, defining explicit states and transitions. Unistore, on the other hand, provides a simpler API for managing state, making it easier to get started but potentially less powerful for complex scenarios.
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
unistore
A tiny 350b centralized state container with component bindings for Preact & React.
- Small footprint complements Preact nicely (unistore + unistore/preact is ~650b)
- Familiar names and ideas from Redux-like libraries
- Useful data selectors to extract properties from state
- Portable actions can be moved into a common place and imported
- Functional actions are just reducers
- NEW: seamlessly run Unistore in a worker via Stockroom
Table of Contents
Install
This project uses node and npm. Go check them out if you don't have them locally installed.
npm install --save unistore
Then with a module bundler like webpack or rollup, use as you would anything else:
// The store:
import createStore from 'unistore'
// Preact integration
import { Provider, connect } from 'unistore/preact'
// React integration
import { Provider, connect } from 'unistore/react'
Alternatively, you can import the "full" build for each, which includes both createStore
and the integration for your library of choice:
import { createStore, Provider, connect } from 'unistore/full/preact'
The UMD build is also available on unpkg:
<!-- just unistore(): -->
<script src="https://unpkg.com/unistore/dist/unistore.umd.js"></script>
<!-- for preact -->
<script src="https://unpkg.com/unistore/full/preact.umd.js"></script>
<!-- for react -->
<script src="https://unpkg.com/unistore/full/react.umd.js"></script>
You can find the library on window.unistore
.
Usage
import createStore from 'unistore'
import { Provider, connect } from 'unistore/preact'
let store = createStore({ count: 0, stuff: [] })
let actions = {
// Actions can just return a state update:
increment(state) {
// The returned object will be merged into the current state
return { count: state.count+1 }
},
// The above example as an Arrow Function:
increment2: ({ count }) => ({ count: count+1 }),
// Actions receive current state as first parameter and any other params next
// See the "Increment by 10"-button below
incrementBy: ({ count }, incrementAmount) => {
return { count: count+incrementAmount }
},
}
// If actions is a function, it gets passed the store:
let actionFunctions = store => ({
// Async actions can be pure async/promise functions:
async getStuff(state) {
const res = await fetch('/foo.json')
return { stuff: await res.json() }
},
// ... or just actions that call store.setState() later:
clearOutStuff(state) {
setTimeout(() => {
store.setState({ stuff: [] }) // clear 'stuff' after 1 second
}, 1000)
}
// Remember that the state passed to the action function could be stale after
// doing async work, so use getState() instead:
async incrementAfterStuff(state) {
const res = await fetch('foo.json')
const resJson = await res.json()
// the variable 'state' above could now be old,
// better get a new one from the store
const upToDateState = store.getState()
return {
stuff: resJson,
count: upToDateState.count + resJson.length,
}
}
})
// Connecting a react/preact component to get current state and to bind actions
const App1 = connect('count', actions)(
({ count, increment, incrementBy }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={() => incrementBy(10)}>Increment by 10</button>
</div>
)
)
// First argument to connect can also be a string, array or function while
// second argument can be an object or a function. Here we pass an array and
// a function.
const App2 = connect(['count', 'stuff'], actionFunctions)(
({ count, stuff, getStuff, clearOutStuff, incrementAfterStuff }) => (
<div>
<p>Count: {count}</p>
<p>Stuff:
<ul>{stuff.map(s => (
<li>{s.name}</li>
))}</ul>
</p>
<button onClick={getStuff}>Get some stuff!</button>
<button onClick={clearOutStuff}>Remove all stuff!</button>
<button onClick={incrementAfterStuff}>Get and count stuff!</button>
</div>
)
)
export const getApp1 = () => (
<Provider store={store}>
<App1 />
</Provider>
)
export const getApp2 = () => (
<Provider store={store}>
<App2 />
</Provider>
)
Debug
Make sure to have Redux devtools extension previously installed.
import createStore from 'unistore'
import devtools from 'unistore/devtools'
let initialState = { count: 0 };
let store = process.env.NODE_ENV === 'production' ? createStore(initialState) : devtools(createStore(initialState));
// ...
Examples
API
createStore
Creates a new store, which is a tiny evented state container.
Parameters
state
Object Optional initial state (optional, default{}
)
Examples
let store = createStore();
store.subscribe( state => console.log(state) );
store.setState({ a: 'b' }); // logs { a: 'b' }
store.setState({ c: 'd' }); // logs { a: 'b', c: 'd' }
Returns store
store
An observable state container, returned from createStore
action
Create a bound copy of the given action function.
The bound returned function invokes action() and persists the result back to the store.
If the return value of action
is a Promise, the resolved value will be used as state.
Parameters
action
Function An action of the formaction(state, ...args) -> stateUpdate
Returns Function boundAction()
setState
Apply a partial state object to the current state, invoking registered listeners.
Parameters
update
Object An object with properties to be merged into stateoverwrite
Boolean Iftrue
, update will replace state instead of being merged into it (optional, defaultfalse
)
subscribe
Register a listener function to be called whenever state is changed. Returns an unsubscribe()
function.
Parameters
listener
Function A function to call when state changes. Gets passed the new state.
Returns Function unsubscribe()
unsubscribe
Remove a previously-registered listener function.
Parameters
listener
Function The callback previously passed tosubscribe()
that should be removed.
getState
Retrieve the current state object.
Returns Object state
connect
Wire a component up to the store. Passes state as props, re-renders on change.
Parameters
mapStateToProps
(Function | Array | String) A function mapping of store state to prop values, or an array/CSV of properties to map.actions
(Function | Object)? Action functions (pure state mappings), or a factory returning them. Every action function gets current state as the first parameter and any other params next
Examples
const Foo = connect('foo,bar')( ({ foo, bar }) => <div /> )
const actions = { someAction }
const Foo = connect('foo,bar', actions)( ({ foo, bar, someAction }) => <div /> )
Returns Component ConnectedComponent
Provider
Extends Component
Provider exposes a store (passed as props.store
) into context.
Generally, an entire application is wrapped in a single <Provider>
at the root.
Parameters
props
Objectprops.store
Store A {Store} instance to expose via context.
Reporting Issues
Found a problem? Want a new feature? First of all, see if your issue or idea has already been reported. If not, just open a new clear and descriptive issue.
License
Top Related Projects
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