npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

feature-state

v0.0.37

Published

Straightforward, typesafe, and feature-based state management library for ReactJs

Downloads

169

Readme

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

📚 Examples

🌟 Motivation

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.

⚖️ Alternatives

📖 Usage

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 { useGlobalState } from 'feature-state-react';
import { $tasks } from '../store/tasks';

export const Tasks = () => {
	const tasks = useGlobalState($tasks);

	return (
		<ul>
			{tasks.map((task) => (
				<li>{task.title}</li>
			))}
		</ul>
	);
};

Atom-based

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

Subscribing to State Changes

You can subscribe to state changes using $state.subscribe(callback), which works in vanilla JS. For React, special hooks like useGlobalState($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.

📙 Features

withStorage()

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 the StorageInterface with methods save, load, and delete for handling the persistence
  • key: The key used to identify the state in the storage medium

withUndo()

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 is 50

withMultiUndo()

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