Skip to content

Getting Started

“Two and eight” — Cockney rhyming slang for “state”.

Introduction

A lightweight JavaScript / TypeScript state management library that uses a class-based store.

Key features include:

  • Action / commit based state flow.
  • Built-in subscription system for reactive updates.
  • Flexible state reset functionality for entire state or specific fields.
  • Type-safe state management.
  • Minimal boilerplate.

Installation

Terminal window
npm i 2n8

Create a store

You store is a class, and turning it into a React hook is as easy as passing it to the createReactStore utility.

store.ts
import { TwoAndEight, createReactStore } from '2n8'
class Store extends TwoAndEight {
expression: '🫤' | '🥸' = '🫤'
addDisguise() {
this.expression = '🥸'
}
resetToConfusion() {
this.$reset('expression')
}
}
export const useStore = createReactStore(new Store())

Import into your React components

The hook provides flexible state management that can be used directly in any component. When you modify the state, the consuming component automatically re-renders to reflect those changes.

Expression.tsx
function Expression() {
const expression = useStore((s) => s.expression)
return <h1>{expression}</h1>
}
App.tsx
function App() {
const addDisguise = useStore((s) => s.addDisguise)
const resetToConfusion = useStore((s) => s.resetToConfusion)
return (
<>
<button onClick={addDisguise}>Hide!</button>
<button onClick={resetToConfusion}>What?!</button>
</>
)
}