Today I Learned - Rocky Kev

TIL SolidJS reactivity

POSTED ON:

TAGS:

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());
});
  1. We are creating count and setCount, which are the getters/Setters of our createSignal() function

  2. In setTimeout, we are calling our setCount setter, which will equal to the getter + 1. (or count() + 1) Every second, add another one to it.

  3. In our createEffect(), we then want that data to show somehow.

  4. 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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.