helix

stagmoose 2023-09-24T08:02:30.920219Z

When I use the setter inside use-effect, I can see the value of div is 10 initially, And I can also see console print "running use-effect", but the value of div is still 10 not the intended 20 What did I do wrongly?

(defnc app []
  (let [player-ref (hooks/use-ref nil)
        [subtitle set-subtitle] (hooks/use-state 10)
        _ (def debug subtitle)]
    (hooks/use-effect :always
                      (fn []
                        (js/console.log "running use-effect")
                        (set-subtitle 20)
                        ))
    (<>
     (d/h1 {:class "my-8 flex justify-center items-center text-2xl font-bold"} "Sentence Relationships!!")

     (d/div "subtile: " subtitle)
     )))

stagmoose 2023-09-24T11:03:53.406629Z

(defnc Tmp []
  (let [[attr setter] (hooks/use-state 10)]
    (hooks/use-effect :once (fn []
                              (setter 20)))
    (d/div (str "this is tmp comp: " attr))))
for this simple example, i will expect it will render a div with 20, but it turns out it's a div with 10 from what i know, the procedure is first render -> run useEffect -> update state -> trigger rerender -> get a div with 20 didn't know what i missed here.

dvingo 2023-09-24T11:39:18.669469Z

The body does not need to be wrapped in a function. so you have effectively written the following:

(defnc Tmp []
  (let [[attr setter] (hooks/use-state 10)]
    (hooks/use-effect :once nil (fn unmount []
                              (setter 20)))
    (d/div (str "this is tmp comp: " attr))))

1
stagmoose 2023-09-24T11:51:35.127679Z

It works now haha! Didn't notice this is different from useEffect. Thanks dvingo!!

😀 1
🎉 1
lilactown 2023-09-24T16:04:17.113589Z

it was probably printing "running use-effect" when the component was running its cleanup of previous effects during render/unmounting