All Projects → onurkerimov → xoid

onurkerimov / xoid

Licence: MIT license
Framework-agnostic state management library designed for simplicity and scalability ⚛

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to xoid

State Machine Component
⚙️ State machine -powered components in 250 bytes
Stars: ✭ 178 (+85.42%)
Mutual labels:  state-management, preact, state-machine
Pvm
Build workflows, activities, BPMN like processes, or state machines with PVM.
Stars: ✭ 348 (+262.5%)
Mutual labels:  state-management, state-machine
Redux Machine
A tiny library (12 lines) for creating state machines in Redux apps
Stars: ✭ 338 (+252.08%)
Mutual labels:  state-management, state-machine
React Context Hook
A React.js global state manager with Hooks
Stars: ✭ 50 (-47.92%)
Mutual labels:  state-management, state-machine
statebot
Write more robust and understandable programs. Statebot hopes to make Finite State Machines a little more accessible.
Stars: ✭ 24 (-75%)
Mutual labels:  state-management, state-machine
zedux
⚡ A high-level, declarative, composable form of Redux https://bowheart.github.io/zedux/
Stars: ✭ 43 (-55.21%)
Mutual labels:  state-management, state-machine
Little State Machine
📠 React custom hook for persist state management
Stars: ✭ 654 (+581.25%)
Mutual labels:  state-management, state-machine
useStateMachine
The <1 kb state machine hook for React
Stars: ✭ 2,231 (+2223.96%)
Mutual labels:  state-management, state-machine
Zproc
Process on steroids
Stars: ✭ 112 (+16.67%)
Mutual labels:  state-management, state-machine
Freactal
Clean and robust state management for React and React-like libs.
Stars: ✭ 1,676 (+1645.83%)
Mutual labels:  state-management, preact
xstate-cpp-generator
C++ State Machine generator for Xstate
Stars: ✭ 33 (-65.62%)
Mutual labels:  state-management, state-machine
Use Machine
React Hook for using Statecharts powered by XState. use-machine.
Stars: ✭ 226 (+135.42%)
Mutual labels:  state-management, state-machine
xstate-viz
Visualizer for XState machines
Stars: ✭ 274 (+185.42%)
Mutual labels:  state-management, state-machine
Beedle
A tiny library inspired by Redux & Vuex to help you manage state in your JavaScript apps
Stars: ✭ 329 (+242.71%)
Mutual labels:  state-management, state-machine
stoxy
Stoxy is a state management API for all modern Web Technologies
Stars: ✭ 73 (-23.96%)
Mutual labels:  state-management, preact
Machinery
State machine thin layer for structs (+ GUI for Phoenix apps)
Stars: ✭ 367 (+282.29%)
Mutual labels:  state-management, state-machine
fs2-es
Event sourcing utilities for FS2
Stars: ✭ 75 (-21.87%)
Mutual labels:  state-management, state-machine
preact-urql
Preact bindings for urql
Stars: ✭ 28 (-70.83%)
Mutual labels:  state-management, preact
When Ts
When: recombinant design pattern for state machines based on gene expression with a temporal model
Stars: ✭ 112 (+16.67%)
Mutual labels:  state-management, state-machine
Hydux
A light-weight type-safe Elm-like alternative for Redux ecosystem, inspired by hyperapp and Elmish
Stars: ✭ 216 (+125%)
Mutual labels:  state-management, preact

Bundle Size Version Downloads Netlify License

xoid is a framework-agnostic state management library. X in its name signifies the inspiration it draws from great projects such as ReduX, MobX and Xstate. It was designed to be simple and scalable. It has extensive Typescript support.

xoid is lightweight (~1kB gzipped), but quite powerful. It's composed of building blocks for advanced state management patterns. One of the biggest aims of xoid is to unify global state, local component state, and finite state machines in a single API. While doing all these, it also aims to keep itself approachable for newcomers. More features are explained below, and the documentation website.

To install, run the following command:

npm install xoid

or

yarn add xoid

Examples

Quick Tutorial

xoid has only one export: create. Create is also exported as the default export.

import { create } from 'xoid' import create from 'xoid'

Atom

Atoms are holders of state.

import { create } from 'xoid'

const atom = create(3)
console.log(atom.value) // 3
atom.set(5)
atom.update((state) => state + 1)
console.log(atom.value) // 6

Atoms can have actions if the second argument is used.

import { create } from 'xoid'

const numberAtom = create(5, (atom) => ({
  increment: () => atom.update(s => s + 1),
  decrement: () => atom.update(s => s - 1)
}))

numberAtom.actions.increment()

There's the .focus method, which can be used as a selector/lens. xoid is based on immutable updates, so if you "surgically" set state of a focused branch, changes will propagate to the root.

import { create } from 'xoid'

const atom = create({ deeply: { nested: { alpha: 5 } } })
const previousValue = atom.value

// select `.deeply.nested.alpha`
const alphaAtom = atom.focus(s => s.deeply.nested.alpha)
alphaAtom.set(6)

// root state is replaced with new immutable state
assert(atom.value !== previousValue) // ✅
assert(atom.value.deeply.nested.alpha === 6) // ✅

Derived state

Atoms can be derived from other atoms. This API was heavily inspired by Recoil.

const alpha = create(3)
const beta = create(5)
// derived atom
const sum = create((get) => get(alpha) + get(beta))

Alternatively, .map method can be used to quickly derive the state from a single atom.

const alpha = create(3)
// derived atom
const doubleAlpha = alpha.map((s) => s * 2)

Subscriptions

For subscriptions, subscribe and watch are used. They are the same, except watch runs the callback immediately, while subscribe waits for the first update after subscription.

const unsub = atom.subscribe(
  (state, previousState) => { console.log(state, previousState) }
)

// later
unsub()

To cleanup side-effects, a function can be returned in the subscriber function. (Just like React.useEffect)

React integration

@xoid/react is based on two hooks. useAtom subscribes the component to an atom. If a second argument is supplied, it'll be used as a selector function.

import { useAtom } from '@xoid/react'

// in a React component
const state = useAtom(atom)

The other hook is useSetup. It can be used for creating local component state. It's similar to React.useMemo with empty dependencies array. It'll run its callback only once.

import { useSetup } from '@xoid/react'

const App = () => {
  const $counter = useSetup(() => create(5))

  ...
}

useSetup is guaranteed to be non-render-causing. Atoms returned by that should be explicitly subscribed via useAtom hook.

An outer value can be supplied as the second argument. It'll turn into a reactive atom.

import { useSetup } from '@xoid/react'

const App = (props: Props) => {
  const setup = useSetup(($props) => {
    // `$props` has the type: Atom<Props>
    // this way, we can react to `props.something` as it changes
    $props.focus(s => s.something).subscribe(console.log)
  }, props)

  ...
}

If you've read until here, you have enough knowledge to start using xoid. You can refer to the documentation website for more.

More features

Pattern: Finite state machines

No additional syntax is required for state machines. Just use the good old create function.

import { create } from 'xoid'
import { useAtom } from '@xoid/react'

const createMachine = () => {
  const red = { color: '#f00', onClick: () => atom.set(green) }
  const green = { color: '#0f0', onClick: () => atom.set(red) }
  const atom = create(red)
  return atom
}

// in a React component
const { color, onClick } = useAtom(createMachine)
return <div style={{ color }} onClick={onClick} />

Redux Devtools integration

Import @xoid/devtools and set a debugValue to your atom. It will send values to the Redux Devtools Extension.

import { devtools } from '@xoid/devtools'
import { create, use } from 'xoid'
devtools() // run once

const atom = create(
  { alpha: 5 }, 
  (atom) => {
    const $alpha = atom.focus(s => s.alpha)
    return {
      inc: () => $alpha.update(s => s + 1),
      resetState: () => atom.set({ alpha: 5 })
      deeply: {
        nested: {
          action: () => $alpha.set(5)
        }
      } 
    }
  }
)

atom.debugValue = 'myAtom' // enable watching it by the devtools

const { deeply, incrementAlpha } = atom.actions // destructuring is no problem
incrementAlpha() // logs "(myAtom).incrementAlpha"
deeply.nested.action() // logs "(myAtom).deeply.nested.action"
atom.focus(s => s.alpha).set(25)  // logs "(myAtom) Update ([timestamp])

Why xoid?

  • Easy to learn
  • Small bundle size
  • Framework-agnostic
  • Extensive Typescript support
  • Easy to work with nested states
  • Computed values, transient updates
  • Can be used to express finite state machines
  • No middleware is required for async/generator stuff
  • Global state and local component state in the same API

Other packages

  • @xoid/react - React integration
  • @xoid/devtools - Redux Devtools integration
  • @xoid/lite - Lighter version with less features
  • @xoid/feature - A typesafe plugin system oriented in ES6 classes

Thanks

Following awesome projects inspired xoid a lot.

Thanks to Anatoly for the pencil&ruler icon #24975.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].