Unravel Reactivity in 16 lines of Vanilla JS

Michele Rullo
2 min readOct 22, 2022
Credits: pexels.com

You are a frontend engineer.

You are using React, Vue or Svelte every day to get your job done and be praised by your boss.

Sometimes you wondered what’s behind the post-JQuery revolution that led all of us to this new Reactivity madness.

But you keep telling yourself you got no time to explore what’s behind.

Well, you’re lucky! I built a super simple-tiny-easy-peasy reactive tool in 16 lines (line-breaks included) so you don’t have to.

If you’re impatient, here’s your code: https://jsfiddle.net/Mikepicker/3hms9tr5/

Let’s get on it.

The Mission

We would like to be able to somehow mark html elements with a specific key, so that whenever I change the value associated to such key all elements associated to it will change in a “reactive” fashion.

The idea is to keep track of the elements displayed on the page (indexed by the reactive attribute) and automatically update their value as soon as an event occurs (e.g. due to an onchange or fetch event).

The Code

We’ll fetch a REST API every 5 seconds which will reactively change a specific HTML element.

Also, a couple of paragraphs will be automagically updated as soon as you type on the input box.

Let’s unroll this:

  1. We go through all the elements containing the reactive attribute (line 20). We’ll use the value of such attribute as a key to lookup the elements that we need to update as soon as data changes.
  2. We initialize an object containing a list of such elements and a Proxy to keep track of data changes (line 22).
  3. We store all the HTML elements associated to the specific key and initialize the Proxy responsible to intercept data change and updating the HTML elements accordingly (lines 23–29).
  4. We expose a render function which we can call from anywhere in order to update specific data (and, thus, the associated HTML elements).

As you can see, on line 14 we can simply call render('key', 'value') to automatically update all the elements associated to that key.

Also, we can trigger render(...) as soon as a fetch call returns the response.

You can play with the code here: https://jsfiddle.net/Mikepicker/3hms9tr5/

Wrapping Up

That’s it! It definitely isn’t the next ReactJS, but we’re pretty close, right? :D

I hope these few lines triggered your inner curiosity!

Cheers!

💗 If you like what you’ve read feel free to leave a comment
👏 Claps are always appreciated and..
🔖 …don’t forget to subscribe!

--

--

Michele Rullo

Head of Technical Services @keyless.io / Computer Engineer / Guitarist / Sailing