DEV Community

Cover image for Own state manager in 80 lines
Sergey S. Volkov
Sergey S. Volkov

Posted on • Edited on

Own state manager in 80 lines

Reffect

GitHub logo acacode / reffect

The state manager

reffect logo
npm npm bundle size license

Reffect — is a declarative and reactive multi-store state manager for JavaScript/TypeScript applications inspired by Reatom and Effector

Packages

Install

Before at all you need to install the main package:

$ npm i -S @reffect/core
# or using yarn
$ yarn install @reffect/core

If a project is using React you need to install @reffect/react (pack of React hooks which simplify usage with React application)

$ npm i -S @reffect/react

Examples

Simple counter

import { store, effect, manage } from "@reffect/core";
const counter = store({ value: 0 });
const

My goal was to create new state manager which will be more simpler than all other alternatives.

Package have three exports - createStore, effect and manageStore and that's all.

with createStore we are creating a store.
effect() create a store's "effect" which will update store.
State of store contains in return value from createStore function.
manageStore is needed for subscribe on store changes.

Sounds simple, take a look how it looks in practice :)

For example we have a library with books.
First of all we should create a store

import { createStore } from "@reffect/core"

const books = createStore({
  all: [],
  selected: null,
})

Now we have a books store. We can use state just using books variable

const filtered = books.all.filter(book => book.genre === "classic")

But we need add some books into the store. Lets do that via effect()

import { effect } from "@reffect/core"

const addBook = effect(books, book => ({
  ...books,
  all: [...books.all, book],
}))

addBook({
  author: "E.B. White",
  name: "Charlotte's Web",
  year: 1952,
  genre: "fantasy",
})

console.log(books.all) // [{ ... Charlotte's Web }]

Also we can combine effects


const setBooks = effect(books, "all")

const addBook = effect(books, book => setBooks([...books.all, book]))

There's no need any reducers or actions. We have only effect which is action and reducer. Also all created effects return void

setBooks([]) // returns undefined

Conclusion

It's not a redux killer. Just I've created it to have a minimal bundle size of my frontend application and make state management more simpler for me.

Currently it still may have bugs and problems but I already use it in my personal projects.

Top comments (0)