DEV Community

Discussion on: How State Management works? Dead simple SM in Vanilla JavaScript

 
sgroen profile image
Viridi

Hi Vijay Pushkin,

You are absolutely right. artydev and Matt Kimek started a discussion about optimization. I just hooked in to that. Your post was about handling state in vanilla javascript and you did a good job on that.

Thread Thread
 
artydev profile image
artydev • Edited

And only for the pleasure , here is a case when using a library worth it :-)

<div class="my-chrono"></div>
<div class="my-chrono"></div>
<div class="my-chrono"></div>
<div class="my-chrono"></div>
<div class="my-chrono"></div>
<div class="my-chrono"></div>
Enter fullscreen mode Exit fullscreen mode
import {define} from 'wicked-elements';

let Counter = function () {
  let count = 0;  
  let disabled = false;
  let timer;
  let start = () => {timer = setInterval(() => { count += 1; disabled = true; m.redraw()}) };
  let stop = () => {clearInterval(timer); disabled = false; m.redraw()};
  let reset = () => {stop(); count = 0};
  let disable = (status) => status;
  let view = () => [
    m(".wrap", 
      m("h1",  count ), 
        m("",
        m("button", {onclick : start, disabled : disabled}, "start"),
        m("button", {onclick : stop}, "stop"),
        m("button", {onclick : reset}, "reset")
      ) 
    )
  ]
  return  { view }
}

function renderComp(target, component) {
   m.mount(target, component);
}

define(".my-chrono", {
   init() {
     renderComp(this.element, Counter);
   } 
})

Enter fullscreen mode Exit fullscreen mode

You can test it here :

MulipleCounters