React component state with Derivable

This is the next article in the series about the Derivable library.

The previous one introduced us to React Derivable which allows to drive React components with derivable values.

This article touches the same topic of using React with Derivable but focuses on a single aspect: React component state implemented with Derivable.

Let’s consider the simplest case for stateful React component, a counter which renders its current values along with a button to increment it:

import {atom} from 'derivable'
import React from 'react'
import {reactive} from 'react-derivable'
let Counter = reactive(class extends React.Component {
  counter = atom(0)

increment = () => {
this.counter.set(this.counter.get() + 1)
}
  render() {
return (
<div>
<div>{this.counter.get()}</div>
<button onClick={this.increment}>Increment</button>
</div>
)
}
})

This is the complete example.

The value of counter is initialised when the component is created and holds its initial value (zero). Value of the counter is read in render() (which makes component re-render when it changes). We also provide an onClick event handler which updates the atom’s value.

One benefit of using generic state management solutions like Derivable is that it makes it easier to do refactorings which change state ownership.

For example, let’s hoist the counter state one level up:

import {atom} from 'derivable'
import React from 'react'
import {reactive} from 'react-derivable'
let CounterState = reactive(class extends React.Component {
  counter = atom(0)

increment = () => {
this.counter.set(this.counter.get() + 1)
}
  render() {
return (
<Counter
counter={this.counter.get()}
increment={this.increment}
/>
)
}
}
let Counter = (props) => 
<div>
<div>{props.counter}</div>
<button onClick={props.increment}>Increment</button>
</div>

The only code we moved is the code related to the state itself: the refactoring is mechanical in its nature.

The next step is to implement more powerful state management patterns like Flux / Redux.

Stay tuned.

Like what you read? Give Andrey Popp a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.