When should you use swap or reset

What is the difference between using swap! and reset! in Clojure functions? I saw from clojure.core docs that they are used to change the value of an atom, but I'm not sure when to use swap! and when to use reset! .

In what circumstances would you use swap! and what circumstances would you use reset! ?

 [:input {:type "text" :value @time-color :on-change #(reset! time-color (-> % .-target .-value))}] 

The above code is an example of using reset! for button

 [:input.form-control {:type :text :name :ric :on-change #(swap! fields assoc :ric (-> % .-target .-value)) :value (:ric @fields)}] 

And this button uses swap!

Are swap! and reset! interchangeable?

thanks

+6
source share
1 answer

swap! uses a function to change the value of an atom. Usually you use swap! when the current value of the atom matters. For example, increasing the value depends on the current value, so you should use the inc function.

reset! just sets the value of the atom to some new value. You will usually use this when you just want to set the value without worrying about what the current value is.

 (def x (atom 0)) (swap! x inc) ; @x is now 1 (reset! x 100) ; @x is now 100 (swap! x inc) ; @x is now 101 
+15
source

Source: https://habr.com/ru/post/1012698/


All Articles