clojurescript Getting Started with Reagent Reagent Atoms


Reagent atoms are essentially the same as regular atoms in both Clojure and ClojureScript - they are essentially variables that can be altered. This is especially useful, as Clojure(Script)'s data types are mostly immutable - which means that to change the value of a variable, the variable has to be redeclared.

Normal atoms are incompatible with Reagent, and so Reagent has its own. They are declared like normal variables, except with an additional function wrapped around the value:

(:require [reagent.core :as r])

(def num (r/atom 1))

You can get the value of an atom in two ways:

(deref num) ; => 1
@num        ; => 1

To change the value of an atom, there are two commands, swap! and reset!.

  • swap! is given commands, changes the atom's value based on the original value of the atom itself
  • reset! is given a value, and changes the atom's value to the value given, regardless of what the atom was originally
(swap! num inc) ; => (inc num) => num = 2
(reset! num 5)  ; => num = 5