Managing State with Re-Frame

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (29 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Build the UI with Reagent | TOC | What You’ve Lear ned 👉

The most popular Reagent-based framework is re-frame. Re-frame places all its state in one global atom which it calls the app-db. The only way to read from the app-db is using re-frame subscriptions, and the only way to write to the app-db is by dispatching re-frame events. Note that even though the app-db can only be accessed this way, we can still include regular Reagent atoms in a re-frame application and manage them ourselves.

Let’s get re-frame set up in our guestbook application so we can see how it works. First, just like we did with cljs-ajax, let’s add it to our project’s dependencies:

guestbook-rf-intro/project.clj

​ [cljs-ajax ​"0.8.1"​]
​ [org.clojure/clojurescript ​"1.10.764"​ :scope ​"provided"​]
​ [reagent ​"1.0.0"​]
​ [re-frame ​"1.1.2"​] ​;add re-frame​

Restart the ClojureScript compiler:

​ ​$ ​​lein​​ ​​clean​
​ ​$ ​​lein​​ ​​cljsbuild​​ ​​auto​
​ Watching for changes before compiling ClojureScript...

And require it in our namespace declaration:

guestbook-rf-intro/src/cljs/guestbook/core.cljs

​ (​ns​ guestbook.core
​ (:require [reagent.core :as r]
​ [reagent.dom :as dom]
​ [re-frame.core…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.