DEV Community

Cover image for Reagent 101 / why square brackets?
icncsx
icncsx

Posted on

Reagent 101 / why square brackets?

Ever wonder why we use [my-component] instead of (my-component). After all components are just functions, right? This blog post aims to address why we wrap a component name with [] instead of (). This is Clojure after all - where are the ()?

The answer lies in how Reagent processes a Hiccup vector.

How Reagent Interprets Hiccup

(defn child []
  [:h1 "WAAAAH"])

(defn parent []
  [:div
   [child]])
Enter fullscreen mode Exit fullscreen mode

This is what Reagent is thinking when it encounters [child].

Hmm... child is not a valid symbol (e.g. :div, :img), which means that child is a function. I shall call this function if I need to render. If you're curious about what makes a component re-render, check out this post.

If you're coming from a React background, this is the equivalent idea.

conts Child = () => <h1>Hello, world!</h1>
const Parent = () => {
  return (
    <div>
      {Child()}
      <Child />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

It is true that both [fn] and (fn) will ultimately produce the same DOM just as it is the case that in React, it's the same outcome if we Fn() vs <Fn/>. But the key distinction is that [] does not force a render, whereas () does. Square brackets are efficient.

Here is a beautiful quote from Pratley's blog:

If our components called sub components directly, it would force them to always compute a result. We don't want that. Instead we leave the task of calling the component up to Reagent. Reagent will figure out when it needs to evaluate a component.

In React, use <>. In Reagent, use []. Simple as that.

Warmly,
DH

Top comments (0)