Forum Moderators: open
a library for managing and centralizing application state. It is most commonly used with libraries such as React or Angular for building user interfaces.
useInterval() setInterval() So why not just use setInterval directly?
This may not be obvious at first, but the difference between the setInterval you know and my useInterval Hook is that its arguments are “dynamic”.
<h2 class="counterHeading">0</h2>
<input class="intervalInput" type="text" value="600" />
const counterHeading = document.querySelector('.counterHeading');
let counterIntervalInput = document.querySelector('.intervalInput');
const getCounterInterval = () => counterIntervalInput.value;
const getCounterValue = () => parseInt(counterHeading.textContent);
const incrementCounterValue = () => counterHeading.textContent = (getCounterValue() + 1);
let incrementCounter = setInterval(() => incrementCounterValue(), getCounterInterval());
const updateCounterInterval = () => {
clearInterval(incrementCounter);
incrementCounter = setInterval(() => incrementCounterValue(), getCounterInterval());
}
counterIntervalInput.addEventListener('change', updateCounterInterval);
const { render } = ReactDOM;
const Welcome = () => (
<div id="welcome">
<h1>Hello World</h1>
</div>
);
root.render(<Welcome />);
<Welcome />
Instead of building creating and update logic, you just need creation logic and always rebuild the widget. But that's super slow, so you use a virtual DOM to make it faster. Just not as fast as it would have been if you hadn't used the framework.
And notice how short and sweet it is. Compare that to,using vanilla javascript, or even jquery, to do the same thing.
<script setup>
import { ref } from 'vue'
const msg = ref('Hello World!')
</script>
<template>
<h1>{{ msg }}</h1>
<input v-model="msg">
</template>
<h1>Hello World!</h1>
<input type="text" />
<script>
const myHeading = document.querySelector('h1');
const myInput = document.querySelector('input');
myInput.setAttribute('value', myHeading.textContent);
myInput.addEventListener('keyup', () => {myHeading.textContent = myInput.value});
</script>
Compare that to,using vanilla javascript [...] to do the same thing.
What is the point of reactive frameworks [...] ?
I love it when an internal conversation culminates in a fruitful result!