Skip to main content

Quick Start

Creating a new State Manager

First, import StateManager from cotton-box:

import { StateManager } from 'cotton-box'

The StateManager is a class. We can create a new StateManager like this:

interface IUserState {
firstName: string
lastName: string
luckyNumber: number
}

const UserState = new StateManager<IUserState>({
firstName: 'John',
lastName: 'Smith',
luckyNumber: 42,
})

Getting the state

To get the current state, use the .get method.

const user = UserState.get()

To use the State Manager with React, we can import the useStateValue hook and use it like this:

import { useStateValue } from 'cotton-box-react'

function App() {
const user = useStateValue(UserState)
// ...
}

More on using with React.

Setting the state

With a value:

UserState.set(64)

With a function:

UserState.set((state) => ({
...state, // <-- preserve other state properties
luckyNumber: Math.round(Math.random() * 100),
// ^ while only changing the value of `luckyNumber`
}))

Resetting the state

UserState.reset()

tip

It is safe to call all of the State Manager's methods (.get, .set, .reset, etc.) anywhere, both inside and outside of React components.