DEV Community

Cover image for What is Reactivity?

What is Reactivity?

Corbin Crutchley on February 21, 2024

This article is intended for newcomers to HTML and JavaScript programming. However, it's suggested that you read this article explaining what the ...
Collapse
 
efpage profile image
Eckehard

Well explained. Thank you!

Though these frameworks are quite poplar, they have their own challenges. There is simply no sun without shadow!

An event based approach can be a bit more demanding, but it is possible to use it in a much more organized way than you explained. This is your example rewritten in DML:

let count = 0
function update(){
  count = list.children.length
  b1.textContent  = `Add one to: ${ count }` 
  b2.textContent  = `Add one to: ${ count }` 
}

// Build the DOM 
let b1=button()
let b2=button(); br()
let list = ul()
update()

// add Reactivity
b1.onclick = () => { list.add([`List item: ${count+1}`]); update() }
b2.onclick = () => { list.lastChild.remove(); update ()}
Enter fullscreen mode Exit fullscreen mode

A working example is here

Collapse
 
crutchcorn profile image
Corbin Crutchley

There will always be tradeoffs with any approach. Event-based reactivity is still reactivity, however ;)

Collapse
 
efpage profile image
Eckehard

I was thinking if it was possible and useful to mix both approaches. You do this all the time with React, as all DOM elements are stateful, so they preserve their own state and React cares for the state transitions.

We do the same with webcomponents, that also have their own stat logic that is not coupled to any framework and they handle any internal changes very well. Think of a component that changes the background color depending on a given value. Externally, the value can be changed, but the color change is handled internally.

I would call this kind of reactivity "short range reactivity", while more global states that require page changes or manipulation of elements that are not closely coupled the "long range reactivity".

Using events for the "short range logic" seems a good approach to take some load from the state logic. What do you think about this?

Thread Thread
 
crutchcorn profile image
Corbin Crutchley

Not only possible, it's regularly done! Especially with Angular and RxJS. I even wrote a library to use RxJS with React:

crutchcorn.github.io/rxjs-use-hooks/

I'm not sure about the terminology, however. I know there are very specific terms that already exist for this kind of thing but I don't often engage very heavy in it. So long as there's a conceptual understanding I'm okay with having semi-ambigious terminology usage from time-to-time

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

Amazing post 🥰. Love the simplicity of the explanations and the nice illustrations.
This is the reason why I love React and struggle to do anything with vanilla JS 🙈

Collapse
 
crutchcorn profile image
Corbin Crutchley

Thanks so much for the kind words 😊