TIL SolidJS reactivity
POSTED ON:
TAGS: javascript reactivity
SolidJS is a JavaScript framework that supports binding data to elements that it then syncs and displays on web pages.
via What does it mean that Solid.js is truly reactive?
How does Solid's reactivity work?
When you use React, you do things like:
// you use count to get the value
// you use setCount to set the value
const [count, setCount] = useState(0);
// This then displays your getters somewhere
useEffect(() => {
document.title = `You clicked ${count} times`;
});
SolidJS also uses the pub/sub model too.
useState
is createSingal
and
useEffect
is createEffect
We're building it here:
Next, we need to set up our effect. The trick with effects in this pub/sub model is that createEffect will put the function it calls in the global scope so that the signal can capture it as a listener.
let listener; // the function createEffect calls. It's GLOBAL!
function createSignal(initialValue) {
let value = initialValue;
const listeners = []; // the 'backpack'
function getter() {
if (listener) {
listeners.push(listener); // push the function in and saves it
}
return value;
}
function setter(newValue) {
value = newValue;
// runs through each listener element
listeners.forEach((listener) => {
listener(); // fires the element
});
}
return [getter, setter];
}
function createEffect(func) {
listener = func; // takes the function and passes it to listener
func(); // fires the function
listener = undefined; // un-initializes the function
}
Using a real example:
const [count, setCount] = createSignal(0);
setTimeout(() => {
setCount(count() + 1);
}, 1000);
createEffect(() => {
console.log(count());
});
-
We are creating
count
andsetCount
, which are the getters/Setters of ourcreateSignal()
function -
In setTimeout, we are calling our
setCount
setter, which will equal to the getter + 1. (orcount() + 1
) Every second, add another one to it. -
In our
createEffect()
, we then want that data to show somehow. -
Now, whenever we run the setCount, it also fires the Effect!
via What does it mean that Solid.js is truly reactive?
Related TILs
Tagged: javascript