feature-state
is a straightforward, typesafe, and feature-based state management library for ReactJs.
- Lightweight & Tree Shakable: Function-based and modular design (< 1KB minified)
- Fast: Minimal code ensures high performance, and state changes can be deferred in "the bucket"
-
Modular & Extendable: Easily extendable with features like
withStorage()
,withUndo()
, .. - Typesafe: Build with TypeScript for strong type safety
- Standalone: Zero dependencies, ensuring ease of use in various environments
Create a typesafe, straightforward, and lightweight state management library designed to be modular and extendable with features like withStorage()
, withUndo()
, .. Having previously built AgileTs, I realized the importance of simplicity and modularity. AgileTs, while powerful, became bloated and complex. Learning from that experience, I followed the KISS (Keep It Simple, Stupid) principle for feature-state
, aiming to provide a more streamlined and efficient solution. Because no code is the best code.
store/tasks.ts
import { createState } from 'feature-state';
export const $tasks = createState<Task[]>([]);
export function addTask(task: Task) {
$tasks.set([...$tasks.get(), task]);
}
components/Tasks.tsx
import { useFeatureState } from 'feature-state-react';
import { $tasks } from '../store/tasks';
export const Tasks = () => {
const tasks = useFeatureState($tasks);
return (
<ul>
{tasks.map((task) => (
<li>{task.title}</li>
))}
</ul>
);
};
States in feature-state
are atom-based, meaning each state should only represent a single piece of data. They can store various types of data such as strings, numbers, arrays, or even objects.
To create an state, use createState(initialValue)
and pass the initial value as the first argument.
import { createState } from 'feature-state';
export const $temperature = createState(20); // °C
In TypeScript, you can optionally specify the value type using a type parameter.
export type TWeatherCondition = 'sunny' | 'cloudy' | 'rainy';
export const $weatherCondition = createState<TWeatherCondition>('sunny');
To get the current value of the state, use $state.get()
. To change the value, use $state.set(nextValue)
.
$temperature.set($temperature.get() + 5);
You can subscribe to state changes using $state.subscribe(callback)
, which works in vanilla JS. For React, special hooks like useFeatureState($state)
are available to re-render components on state changes.
Listener callbacks will receive the new value as the first argument.
const unsubscribe = $temperature.subscribe((newValue) => {
console.log(`Temperature changed to ${newValue}°C`);
});
Unlike $state.listen(callback)
, $state.subscribe(callback)
immediately invokes the listener during the subscription.
Adds persistence functionality to the state, allowing the state to be saved to and loaded from a storage medium.
import { createState, withStorage } from 'feature-state';
const storage = {
async save(key, value) {
localStorage.setItem(key, JSON.stringify(value));
return true;
},
async load(key) {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : undefined;
},
async delete(key) {
localStorage.removeItem(key);
return true;
}
};
const state = withStorage(createState([]), storage, 'tasks');
await state.persist();
state.addTask({ id: 1, title: 'Task 1' });
-
storage
: An object implementing theStorageInterface
with methodssave
,load
, anddelete
for handling the persistence -
key
: The key used to identify the state in the storage medium
Adds undo functionality to the state, allowing the state to revert to previous values.
import { createState, withUndo } from 'feature-state';
const state = withUndo(createState([]), 50);
state.addTask({ id: 1, title: 'Task 1' });
state.undo();
-
historyLimit
: The maximum number of states to keep in history for undo functionality. The default is50
Adds multi-undo functionality to the state, allowing the state to revert to multiple previous values at once.
import { createState, withMultiUndo, withUndo } from 'feature-state';
const state = withMultiUndo(withUndo(createState([]), 50));
state.addTask({ id: 1, title: 'Task 1' });
state.addTask({ id: 2, title: 'Task 2' });
state.multiUndo(2);
-
count
: The number of undo steps to perform, reverting the state back by the specified number of changes
When passing the state object directly into the listener queue, any subsequent state changes before the queue is processed will affect the state reference in the queued listeners. This means listeners would always capture the latest state value rather than the value at the time they were queued.
For example:
const $counter = createState(0);
$counter.listen((context) => {
// By the time this runs, state._v might be different
// from when the listener was queued
console.log(context.state._v);
});
$counter.set(1); // Queues listener
$counter.set(2); // Changes state before queue processes
If you want to access the state inside the listener, you can simply capture it:
const $counter = createState(0);
$counter.listen(() => {
$counter.set((v) => v + 1);
});
While you can reference $counter
directly in listeners, there's no guarantee about its value since it might have changed between queueing and execution of the listener. That's why using context.value
is the safer approach.
All listeners are processed asynchronously through a priority queue to maintain a consistent execution order. Adding a separate sync listener queue would:
- Disrupt the priority-based execution order
- Add complexity to the mental model (sync vs async execution paths)
- Make state updates less predictable
If you need immediate listener processing, you can disable automatic queue processing and handle it manually:
// Disable automatic queue processing
$counter.set(1, { processListenerQueue: false });
$counter.set(2, { processListenerQueue: false });
// Process the queue when you're ready
await processStateQueue();
Alternatively, we could switch to a fully sync listener queue. However, this would compromise the benefits of asynchronous processing.