Reactivity in JS

Ehsan Movaffagh
2 min readMay 1, 2023

--

Hello there! this is my first story ever, and i am very exited about it :)).

In this story, we will discuss simple reactivity in JavaScript and demonstrate how to implement it. React and Vue are both examples of frameworks that utilize reactivity. With reactivity, any changes to the data will automatically update the DOM.

First, let’s try a simple example of reactivity implementation:

<body>
<div id="counter-value"></div>
<button onclick="incr()"> incr </button>
<button onclick="decr()"> decr </button>
</body>

<script>

let counter = 0


const setCounterValueToDOM = () => {
document.querySelector('#counter-value').innerText = counter
}

setCounterValueToDOM()

const incr = () => {
counter += 1
setCounterValueToDOM()
}

const decr = () => {
counter -= 1;
setCounterValueToDOM()
}

</script>

Our result may look like this:

However, this approach is not recommended because it requires calling the setCounterValueToDOM function every time the value is updated, which is considered bad practice.

To implement reactivity from scratch in JavaScript, we can use a Proxy object. The constructor will receive an initial value for the object, as well as a handler. With this handler, we can observe all changes that occur to the object. let’s rewrite the script section of our code:

const counterHandler = {
set(obj, prop, value) {
obj[prop] = value
setCounterValueToDOM()
return obj
}
}

const counter = new Proxy(
{
value: 0,
},
counterHandler,
)


const setCounterValueToDOM = () => {
document.querySelector('#counter-value').innerText = counter.value
}
setCounterValueToDOM()


const incr = () => {
counter.value += 1
}

const decr = () => {
counter.value -= 1
}

Well, actually, this is a better approach. Our set function handler updates the value of the counter in memory and also updates the DOM after each update.

Hope you enjoy!

--

--

Ehsan Movaffagh
Ehsan Movaffagh

Written by Ehsan Movaffagh

Full-stack engineer, crafting innovative solutions to shape the digital world🚀; https://linkedin.com/in/ehsan-movaffagh

No responses yet