Derivable and React

Derivable is a library which allows one to define reactive computations.

There’s 2 minutes worth intro into Derivable I wrote recently. Feel free to skim over it but the following code snippet should make some sense to you already:

import {atom, derivation} from 'derivable'
let x = atom(1) // mutable cell
let y = atom(2) // another one
let xPlusY = derivation(() => x.get() + y.get()) // computation
xPlusY.react(sum =>
console.log('x + y = ', sum)) // prints sum value
x.set(6) // updates x triggers reactions

The topic of this article is how to use Derivable with React.

There’s a project called React Derivable which implements bindings to React (I’m the author by the way). The usage is straightforward:

import React from 'react'
import {reactive} from 'react-derivable'
let Hello = reactive(props =>
<div>Hello, {}!</div>

Notice that we wrapped the regular React component in the reactive() decorator which produces another component. Component produced by reactive() will re-render when any of the derivable values (atoms or derivations) dereferenced (by calling get() method) from within its render() change.

import ReactDOM from 'react-dom'
import {atom} from 'derivable'
let name = atom('Andrey')
ReactDOM.render(<Hello name={name} />)

Now our <Hello /> component is in the DOM. Let’s change name atom:


This will trigger the re-render and DOM will be updated.

In the next articles we will start by exploring design space for state management in React apps with Derivable. The first step is to implement React local component state.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.