State and Actions
State is initiated using class fields. The class must be extended from 2n8’s parent class which enhances the store with a few utilities.
import { TwoAndEight } from '2n8'
class Store extends TwoAndEight { counter = 0}
State changes are made inside actions, which are simply class methods that mutate the fields.
import { TwoAndEight } from '2n8'
class Store extends TwoAndEight { counter = 0
addButtonClicked() { this.counter++ }}
Generate your React hook:
import { createReactStore, TwoAndEight } from '2n8'
class Store extends TwoAndEight { counter = 0
addButtonClicked() { this.counter++ }}
export const useStore = createReactStore(new Store())
This uses React’s
useSyncExternalStore
hook to subscribe to state changes:
import { useStore } from './store'
const Component = () => { const counter = useStore('counter')
return <div>{counter}</div>}
When, and only when, the selected state changes, the component is rerendered by React. This is more optimal than simply passing state down the component tree via props.
Select and call actions from the store:
import { useStore } from './store'
const Component2 = () => { const addButtonClicked = useStore('addButtonClicked')
return <button onClick={addButtonClicked}>Add</button>}
When actions are called, the current values of all state are emitted to the subscribers at the end of the action.