Implementing Redux with Derivable

Andrey Popp
Learn Derivable
Published in
2 min readSep 2, 2016

In this article we are going to explore an implementation of Redux (a popular flavour of Flux) with Derivable.

Redux vs. Derivable

Excuse me for a click-baity article title. The implementation of Redux we are going to talk about here won’t be complete and there’s no point in that.

Redux itself is pretty useful to be used alongside the Derivable in its current form: that would be the topic for the next article. So there’s no Redux vs. Derivable.

Of course the question of added value of using Derivable with Redux also stands up. We will discuss that later.

Redux architecture

Redux artchitecture is so simple in retrospective. Thus we are going to just show an implementation:

import {atom, derivation} from 'derivable'function createStore(reduce, initialState = {}) {
let store = atom(initialState)
return {
store: derivation(() => store.get())
dispatch: (action) => {
let nextState = reduce(store.get(), action)
store.set(nextState)
}
}
}

That’s all it takes (10 LOC) to impement Redux-like architecture pattern with Derivable. Of course this is an oversimplification: middlewares aren’t supported, for example.

We then could use createApplication to define an application by passing it an initial state and a reducer which takes care of processing actions and turning them into state updates:

let {store, dispatch} = createApplication(
function reduce(state, action) {
if (action.type === 'ADD_TODO') {
return {
...state,
todoList: state.todoList.concat(action.text)
}
} else {
throw new Error('unknown action type: ' + action.type)
}
},
{todoList: []}
)
function addTodo(text) {
dispatch({type: 'ADD_TODO', text})
}

Note that atom which stores state isn’t exposed directly but rather via derivation and a dispatch() function. This disallows direct state mutations.

Bindings to React

The interesting bit is that we don’t need some special bindings to React, we can reuse React Derivable which we discussed in the previous articles.

import React from 'react'
import {reactive} from 'react-derivable'
let TodoList = reactive(props => {
let todoList = store.get().todoList
return (
<div>
<ul>{todoList.map(todo => <li>{todo}</li>)}</ul>
<button onClick={() => addTodo('new todo!')}>
Add todo
</button>
</div>
)
})

That’s one of the advantages of the unified reactive state management layer: we can reuse bits of code between different state management strategies.

But Derivable provides another advantage when using it alongside Redux: an efficient query layer for application state. That’s something we are going to discuss in the next article.

--

--