spark-plugs
v0.2.0
Published
A tiny reactive store with React hooks, time travel via a flux capacitor, and a shallow-compare selector engine.
Readme
spark-plugs
Tiny reactive state "sparks" with React hooks, a selector engine, and time-travel debugging.
Installation
yarn add spark-plugs
# or
npm install spark-plugsPeer dependency: react (version ^18.0.0).
Quick start
Create a spark
import { plug } from "spark-plugs";
const countSpark = plug(0);
// read
const current = countSpark(); // 0
// write
countSpark(1);
countSpark((prev) => prev + 1);Use in React with useSpark
import React from "react";
import { plug, useSpark } from "spark-plugs";
const count = plug(0);
export function Counter() {
const value = useSpark(count);
return (
<button onClick={() => count((n) => n + 1)}>
Count: {value}
</button>
);
}Derived state with engine + useSpark
import { plug, engine, useSpark } from "spark-plugs";
const first = plug("Marty");
const last = plug("McFly");
const fullNameEngine = engine([first, last], (f, l) => `${f} ${l}`);
function Name() {
const fullName = useSpark(fullNameEngine);
return <div>{fullName}</div>;
}Time travel with fluxCapacitor + useFluxCapacitor
import { plug, fluxCapacitor, useFluxCapacitor } from "spark-plugs";
const a = plug(0);
const b = plug(0);
const timeMachine = fluxCapacitor([a, b]);
function TimeTravelControls() {
const { canUndo, canRedo, undo, redo } = useFluxCapacitor(timeMachine);
return (
<div>
<button onClick={undo} disabled={!canUndo}>Undo</button>
<button onClick={redo} disabled={!canRedo}>Redo</button>
</div>
);
}API surface
plug<T>(initial?: T): Spark<T>useSpark(...)— React hook to read sparks and enginesengine(sparks, selector)— derive memoized values from sparksfluxCapacitor(plugs)/useFluxCapacitor(engine)— time travel helpersshallow(a, b)— shallow comparison utilityStore,createStore,store— underlying store utilities
License
MIT
