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

Your 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 the hook into your React components

The hook provides a direct connection to your store. When you modify the state, the consuming component automatically re-renders to reflect those changes.

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