Microcosm
Flux with central, isolated state
Table of Contents
- Documentation
- Overview
- Opinions
- What is it trying to solve?
Overview
Microcosm is a variant of Flux
that makes it easier to control and modify state in a pure,
centralized way. It thinks of stores and actions as stateless
collections of pure functions, keeping all data encapsulated in a
specific instance of Microcosm.
This design seeks to achieve a reasonable trade off between the
simplicity of singletons and the privacy of class instances.
Actions
Actions are simple functions. They are called within the context of
Microcosm, taking the value they return and using it as the parameters
for processing within Stores.
let addPlanet = function (params) {
return params
}
app.push(addPlanet, params)
When an action is pushed, it is placed into a historical record of all
actions that have occurred.
Stores
Stores hold no state; instead they are responsible for writing state
to the repository owned by a Microcosm instance.
This allows stores to be simple collections of pure functions that
transform old data into new data. The register
hook tells Microcosm
what actions a store should respond to:
let Planets = {
register() {
return {
[addPlanet] : this.add
}
},
add(planets, props) {
return planets.concat(props)
}
}
Launching an app
Once stores have been added to a Microcosm, it is ready to begin work.
let app = new Microcosm()
app.addStore(Planets, 'planets')
app.start()
From there, an app's state can be sent down your React component tree:
React.render(<SolarSystem app={ app } planets={ app.state.planets } />, document.body)
Opinions
- Action CONSTANTS are automatically generated by assigning
each Action function a unique
toString
signature under the hood. - Actions dispatch parameters by returning a value or a promise (only
dispatching when it is resolved)
- Actions handle all asynchronous operations. Stores are
synchronous.
- Stores do not contain data, they transform it.
What is it trying to solve?
- State isolation. Requests to render applications server-side should
be as stateless as possible. Client-side libraries (such as
Colonel Kurtz) need easy
containment from other instances on the page.
- Singletons are simple, but make it easy to accidentally share
state. Microcosm keeps data in one place, operating on it
statelessly in other entities.
- Easy extension of core API and layering of features out of the
framework's scope.
Inspiration
Visit code.viget.com to see more projects from Viget.