Storeon

A tiny (185 bytes) event-based Redux-like state manager for React, Preact, ...

README

Storeon


<img src="https://storeon.github.io/storeon/logo.svg" align="right"
     alt="Storeon logo by Anton Lovchikov" width="160" height="142">

A tiny event-based Redux-like state manager for React, Preact,
[Angular], [Vue] and [Svelte].

Small. 180 bytes (minified and gzipped). No dependencies.
  It uses [Size Limit] to control size.
Fast. It tracks what parts of state were changed and re-renders
  only components based on the changes.
Hooks. The same Redux reducers.
Modular. API created to move business logic away from React components.

Read more about Storeon features in [our article].

  1. ``` js
  2. import { createStoreon } from 'storeon'

  3. // Initial state, reducers and business logic are packed in independent modules
  4. let count = store => {
  5.   // Initial state
  6.   store.on('@init', () => ({ count: 0 }))
  7.   // Reducers returns only changed part of the state
  8.   store.on('inc', ({ count }) => ({ count: count + 1 }))
  9. }

  10. export const store = createStoreon([count])
  11. ```

  1. ``` js
  2. import { useStoreon } from 'storeon/react' // or storeon/preact

  3. export const Counter = () => {
  4.   // Counter will be re-render only on `state.count` changes
  5.   const { dispatch, count } = useStoreon('count')
  6.   return <button onClick={() => dispatch('inc')}>{count}</button>
  7. }
  8. ```

  1. ``` js
  2. import { StoreContext } from 'storeon/react'

  3. render(
  4.   <StoreContext.Provider value={store}>
  5.     <Counter />
  6.   </StoreContext.Provider>,
  7.   document.body
  8. )
  9. ```

[our article]: https://evilmartians.com/chronicles/storeon-redux-in-173-bytes
[Size Limit]: https://github.com/ai/size-limit
[Angular]: https://github.com/storeon/angular
[Svelte]: https://github.com/storeon/svelte
[Vue]: https://github.com/storeon/vue

  <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
       alt="Sponsored by Evil Martians" width="236" height="54">


Tools


[@storeon/router](https://github.com/storeon/router)
  tracks links and Back button click and allows you to open
  pages without reloading the whole page.
[@storeon/localstorage](https://github.com/storeon/localstorage)
  saves and restores state to localStorage or sessionStorage.
[@storeon/crosstab](https://github.com/storeon/crosstab)
  synchronizes events between browser tabs.
[@storeon/undo](https://github.com/storeon/undo)
  allows undoing or redoing the latest event.
[@storeon/websocket](https://github.com/storeon/websocket)
  to sync actions through WebSocket.

Third-party tools:

[majo44/storeon-async-router](https://github.com/majo44/storeon-async-router)
  is router with data prefetch, modules lazy load, navigation cancellation,
  and routes modification on the fly.
[mariosant/storeon-streams](https://github.com/mariosant/storeon-streams)
  is side effects management library.
[octav47/storeonize](https://github.com/octav47/storeonize)
  is migrating tool from Redux to Storeon.

Install


  1. ```sh
  2. npm install storeon
  3. ```

If you need to support IE, you need to [compile node_modules] with Babel and
add [Object.assign] polyfill to your bundle. You should have this polyfill
already if you are using React.

  1. ``` js
  2. import assign from 'object-assign'
  3. Object.assign = assign
  4. ```

[compile node_modules]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
[Object.assign]: https://www.npmjs.com/package/object-assign


Store


The store should be created with the createStoreon() function. It accepts a list
of functions.

Each function should accept a store as the only argument and bind their event listeners using store.on().

  1. ``` js
  2. // store/index.js
  3. import { createStoreon } from 'storeon'

  4. import { projects } from './projects'
  5. import { users } from './users'

  6. export const store = createStoreon([projects, users])
  7. ```

  1. ``` js
  2. // store/projects.js

  3. export function projects (store) {
  4.   store.on('@init', () => ({ projects: [] }))

  5.   store.on('projects/add', ({ projects }, project) => {
  6.     return { projects: projects.concat([project]) }
  7.   })
  8. }
  9. ```

The store has 3 methods:

store.get() will return current state. The state is always an object.
store.on(event, callback) will add an event listener.
store.dispatch(event, data) will emit an event with optional data.


Events


There are three built-in events:

@init will be fired in createStoreon. Bind to this event to set the initial state.
@dispatch will be fired on every new action (on store.dispatch() calls
  and @changed events). It receives an array with the event name
  and the event’s data. Can be useful for debugging.
@changed will be fired when any event changes the state.
  It receives object with state changes.

To add an event listener, call store.on() with the event name and a callback function.

  1. ``` js
  2. store.on('@dispatch', (state, [event, data]) => {
  3.   console.log(`Storeon: ${ event } with `, data)
  4. })
  5. ```

store.on() will return a cleanup function. Calling this function will remove
the event listener.

  1. ``` js
  2. const unbind = store.on('@changed', )
  3. unbind()
  4. ```

You can dispatch any other events. Just do not start event names with @.

If the event listener returns an object, this object will update the state.
You do not need to return the whole state, return an object
with changed keys.

  1. ``` js
  2. // users: {} will be added to state on initialization
  3. store.on('@init', () => ({ users:  { } }))
  4. ```

An event listener accepts the current state as the first argument,
optional event object as the second and optional store object as the third.

So event listeners can be reducers as well. As in Redux’s reducers,
your should change immutable.

  1. ``` js
  2. store.on('users/save', ({ users }, user) => {
  3.   return {
  4.     users: { ...users, [user.id]: user }
  5.   }
  6. })

  7. store.dispatch('users/save', { id: 1, name: 'Ivan' })
  8. ```

You can dispatch other events in event listeners. It can be useful for async
operations.

  1. ``` js
  2. store.on('users/add', async (state, user) => {
  3.   try {
  4.     await api.addUser(user)
  5.     store.dispatch('users/save', user)
  6.   } catch (e) {
  7.     store.dispatch('errors/server-error')
  8.   }
  9. })
  10. ```


Components


For functional components, the useStoreon hook will be the best option:

  1. ``` js
  2. import { useStoreon } from 'storeon/react' // Use 'storeon/preact' for Preact

  3. const Users = () => {
  4.   const { dispatch, users, projects } = useStoreon('users', 'projects')
  5.   const onAdd = useCallback(user => {
  6.     dispatch('users/add', user)
  7.   })
  8.   return <div>
  9.     {users.map(user => <User key={user.id} user={user} projects={projects} />)}
  10.     <NewUser onAdd={onAdd} />
  11.   </div>
  12. }
  13. ```

For class components, you can use the connectStoreon() decorator.

  1. ``` js
  2. import { connectStoreon } from 'storeon/react' // Use 'storeon/preact' for Preact

  3. class Users extends React.Component {
  4.   onAdd = () => {
  5.     this.props.dispatch('users/add', user)
  6.   }
  7.   render () {
  8.     return <div>
  9.       {this.props.users.map(user => <User key={user.id} user={user} />)}
  10.       <NewUser onAdd={this.onAdd} />
  11.     </div>
  12.   }
  13. }

  14. export default connectStoreon('users', 'anotherStateKey', Users)
  15. ```

useStoreon hook and connectStoreon() accept the list of state keys to pass
into props. It will re-render only if this keys will be changed.


DevTools


Storeon supports debugging with [Redux DevTools Extension].

  1. ``` js
  2. import { storeonDevtools } from 'storeon/devtools';

  3. const store = createStoreon([
  4.   
  5.   process.env.NODE_ENV !== 'production' && storeonDevtools
  6. ])
  7. ```

DevTools will also warn you about typo in event name. It will throw an error
if you are dispatching event, but nobody subscribed to it.

Or if you want to print events to console you can use the built-in logger.
It could be useful for simple cases or to investigate issues in error trackers.

  1. ``` js
  2. import { storeonLogger } from 'storeon/devtools';

  3. const store = createStoreon([
  4.   
  5.   process.env.NODE_ENV !== 'production' && storeonLogger
  6. ])
  7. ```

[Redux DevTools Extension]: https://github.com/zalmoxisus/redux-devtools-extension


TypeScript


Storeon delivers TypeScript declarations which allows to declare type
of state and optionally declare types of events and parameter.

If a Storeon store has to be fully type safe the event types declaration
interface has to be delivered as second type to createStore function.

  1. ```typescript
  2. import { createStoreon, StoreonModule } from 'storeon'
  3. import { useStoreon } from 'storeon/react' // or storeon/preact

  4. // State structure
  5. interface State {
  6.   counter: number
  7. }

  8. // Events declaration: map of event names to type of event data
  9. interface Events {
  10.   // `inc` event which do not goes with any data
  11.   'inc': undefined
  12.   // `set` event which goes with number as data
  13.   'set': number
  14. }

  15. const counterModule: StoreonModule<State, Events> = store => {
  16.   store.on('@init', () => ({ counter: 0}))
  17.   store.on('inc', state => ({ counter: state.counter + 1}))
  18.   store.on('set', (state, event) => ({ counter: event}))
  19. }

  20. const store = createStoreon<State, Events>([counterModule])

  21. const Counter = () => {
  22.   const { dispatch, count } = useStoreon<State, Events>('count')
  23.   // Correct call
  24.   dispatch('set', 100)
  25.   // Compilation error: `set` event do not expect string data
  26.   dispatch('set', "100")
  27.   
  28. }

  29. // Correct calls:
  30. store.dispatch('set', 100)
  31. store.dispatch('inc')

  32. // Compilation errors:
  33. store.dispatch('inc', 100)   // `inc` doesn’t have data
  34. store.dispatch('set', "100") // `set` event do not expect string data
  35. store.dispatch('dec')        // Unknown event
  36. ```

In order to work properly for imports, consider adding
allowSyntheticDefaultImports: true to tsconfig.json.

Server-Side Rendering


In order to preload data for server-side rendering, Storeon provides the
customContext function to create your own useStoreon hooks that
depend on your custom context.

  1. ``` js
  2. // store.jsx
  3. import { createContext, render } from 'react' // or preact

  4. import { createStoreon, StoreonModule } from 'storeon'
  5. import { customContext } from 'storeon/react' // or storeon/preact

  6. const store =

  7. const CustomContext = createContext(store)

  8. // useStoreon will automatically recognize your storeon store and event types
  9. export const useStoreon = customContext(CustomContext)

  10. render(
  11.   <CustomContext.Provider value={store}>
  12.     <Counter />
  13.   </CustomContext.Provider>,
  14.   document.body
  15. )
  16. ```

  1. ``` js
  2. // children.jsx
  3. import { useStoreon } from '../store'

  4. const Counter = () => {
  5.   const { dispatch, count } = useStoreon('count')

  6.   dispatch('set', 100)
  7.   
  8. }
  9. ```


Testing


Tests for store can be written in this way:

  1. ``` js
  2. it('creates users', () => {
  3.   let addUserResolve
  4.   jest.spyOn(api, 'addUser').mockImplementation(() => new Promise(resolve => {
  5.     addUserResolve = resolve
  6.   }))
  7.   let store = createStoreon([usersModule])

  8.   store.dispatch('users/add', { name: 'User' })
  9.   expect(api.addUser).toHaveBeenCalledWith({ name: 'User' })
  10.   expect(store.get().users).toEqual([])

  11.   addUserResolve()
  12.   expect(store.get().users).toEqual([{ name: 'User' }])
  13. })
  14. ```

We recommend to keep business logic away from components. In this case,
UI kit (special page with all your components in all states)
will be the best way to test components.

For instance, with [UIBook] you can mock store and show notification
on any dispatch call.

[UIBook]: https://github.com/vrizo/uibook/