Single atom state tree buzzword explained

If you’ve been following React community for at least last half a year or so, you probably have heard of a buzzword, which is in the title of this article. For React folks it’s a straight sign that here we are using a single storage for application state, not multiple, as it’s common in traditional Flux. But why it’s called “atom”?

The atom is a real thing in Clojure world. And it came into JavaScript minds thanks to ClojureScript’s Om library, which is an interface into React. Om takes advantages of a single global state from day one. And in Om one should put application state into that atom. You can think of atom as an object which holds some value and a references to it.

Here we create atom which holds a map, and assign it to variable with a name of state.

(def state (atom {:name "John Doe"}))

To read the value from atom, it should be dereferenced. It means getting the value behind the reference. This will return the latest value of atom.

(deref state)

Atoms has special functions to mutate their value. One of them is swap!. It takes atom, function that performs mutation and a list of arguments which will be passed into that function along with a value of atom.

(swap! state assoc :name "Rich Hickey")

In some way atom is similar to Store concept in Flux. It’s possible to subscribe to changes in atom. Every time the change was made, the watcher function will be called. The callback will receive the name of the watcher, atom itself, previous value of atom and a new value.

(add-watch state :name
(fn [key ref prev-state new-state]
(println (str "New name is " (:name new-state)))))

This is very similar to how React component can be subscribed to a store in Flux, and then re-render itself on every change which is being made in the store. You could subscribe only a root component and re-render entire application. This is a known technique called top-down rendering.

So atom is not just a raw data structure. It’s a reference to a value with a set of defined operations on that value and subscription mechanism.