Reactivity
About
Reactivity in the framework is understood as the ability, in response to data changes, to automatically update parts of the javascript code or HTML nodes that used this data.
Reactivity example
Before string interpolation
<div class="{ {component_text} }">
{ {component_text} }
</div>
After string interpolation <div class="text">
text
</div>
<div class="text">
text
</div>
After updating data
<div class="text1">
text1
</div>
In this example, the DOM nodes seem to depend on the data that is updated in the data property in the components.
This can also be shown in a diagram:
This diagram shows that data is updated when you use a function that updates it. That is, it is as if a single-threaded data update is being created. In future versions, the structure may change slightly due to the processing of asynchronous data.
With VDOM vs without VDOM
The main advantage of the virtual DOM is that it is a lightweight version of the real DOM, which can be manipulated and the real DOM can be updated only after the virtual DOM is ok. This lightness allows you to avoid updating the real DOM once again, which allows you to update the site relatively quickly.
Frameworks with this technology are quite fast, if not the fastest. But the funny thing is that this layer still creates a barrier between the real DOM and the code, and also takes up memory with an essentially unnecessary object, which creates additional problems.
In practice, working with a real DOM can also be comparable in speed to a virtual one.
This example examines the speed result of the beta version of Cample.js, which, of course, lags behind implementations with a virtual DOM in speed, but still the results are not so bad, which makes it possible to assume that this structure without a virtual DOM is quite possible
Example
const newComponent = component(
"new-component",
`<div class="component">
<div> class="clicks" data-value="{ {dynamicData} }">Clicks:{ {dynamicData} }</div>
<button> class="button">Click</button>
</div>`,
{
script: ({ element, functions }) => {
const button = element.querySelector(".button");
const updateFunction = () => {
functions?.updateClicks((data) => {
return data + 1;
});
};
button.addEventListener("click", updateFunction);
},
data: () => {
return {
dynamicData: 0,
};
},
dataFunctions: {
updateClicks: "dynamicData",
},
}
);
cample("#page", {
trimHTML: true,
}).render(
`
<template> data-cample="new-component"></template>
`,
{
newComponent,
}
);