← Back
jsx react

How JSX works (internally)

TL;DR 1: JSX doesn't invoke custom tags

TL;DR 2: You don't have to worry about really big components

Coming from other frameworks, the React mental model could be a little bit suspicious. Let me explain.

Most of React developers (all?) knows that JSX is translated to actual function calls. For example, the following JSX:

  <div>
<h1>Hola mundo!</h1>
<p>Bienvenidxs!</p>
<button onClick={sayHi}>pulsa aquĆ­ para continuar</button>
</div>

Is translated to:

React.createElement("div", null, 
React.createElement("h1", null, "Hola mundo!"),
React.createElement("p", null, "Bienvenidxs!"),
React.createElement("button", { onClick: sayHi }, "pulsa aqu\xED para continuar")
);

We also know that this result is diffed against the actual DOM, so the browser update work is reduced to the minimum.

But sometimes we got a really big rendering function. Router is a good example of this:

<Router>
<Route path="/"><HomePage /></Route>
<Route path="/account"><UserAccountPage /></Route>
<Route path="/albums"><AlbumListPage /></Route>
<Route path="/album/:id"><AlbumPage /></Route>
...
</Router>

Do we really have to render the whole application to then perform the diff?

The answer is no.

The key thing here is that when we use custom tags (those that start with a capital letter) the JSX doesn't invoke the function, it just store it.

That is, the following JSX code:

  <div>
<MyComponent />
</div>

Is translated to:

React.createElement("div", null, 
React.createElement(MyComponent, null)
);

Going back to the Router page, the UserAccountPage function is only invoked if the path is "/account".

That means that code like this:

{isOpen && <HugeModal />}

is already optimized because, HugeModal function only will be invoked if isOpen is true.

In summary: stop worrying about rendering performance and just simplify your mental model