DEV Community

Diogo Neves
Diogo Neves

Posted on • Edited on

Reactive templates “automagically”

Bemtv logo

One of the most talked about topics lately in the JavaScript universe is Reactive Programming,
something we see somehow in major UI libraries and frameworks like React, Vue, Svelte, Solid, Angular and others.

This article is not intended to explain reactive programming, however, keep in mind that basically(in world of UI libraries/frameworks) whenever the state changes, the template is checked, updated, and the changes are applied to the DOM.

Obviously, each framework deals with this in its own way, some more reactive, others declarative, with VDOM, without VDOM...

What if we tried to do the opposite of what these frameworks normally do? Instead of changing the state causing the template to be updated, the template itself checks to see if the state has changed and updates itself.

At first it may seem strange, but this is the proposal of the Bemtv library.

A brief look

Counter component:

import { _ } from "bemtv";

const { click$, $, css, template, render } = _`Counter`({ count: 0 });

click$(() => $.count++);

css`
  padding: 20px;
  color: blue;
`;

template`button[Cliked: $count ]`;

render();
Enter fullscreen mode Exit fullscreen mode

It uses a requestAnimationFrame loop to execute just the component template, thus getting the updated template to compare with the previous template to detect if there have been any changes and apply them to the DOM.

We might think that this will overload the browser, however, there are best practices we should follow to avoid this:

  • Everything inside the template must be strings, numbers or light calculations.

  • The function that generates the template should only be used for this.

Bemtv also uses a sophisticated system to determine if there have been any changes to the template, continues using the browser's repaint as a basis, but reduces the number of checks as the user interacts with the page and the time the component takes to generate the template, this makes Bemtv more efficient.

Bemtv does its work at runtime, it has a markup language very similar to HTML basically reducing its redundancy and a CSS-In-JS library all integrated into the template, and a Router full of syntactic sugars.

Bemtv is currently not available for production and its main goal is to be a tool for small web applications that can be learned in minutes instead of hours.

And that’s it

That's it for today, but you can find out more details on project repository and if you like the idea, don't forget to leave your star, it encourages the development of the project, see you soon!

Top comments (0)