Understand "Signals" with Solid JS and Qwik

What is "Signals"?

"Signals" is a new way to manage states in Solid JS and Qwik. The key difference between Signals and States is that Signals return a getter and a setter, whereas non-reactive systems return a value (and a setter). In Solid JS, createSignal can be used to create and subscribe to a signal, while in Qwik, we will use useSignal instead. The usage concept is the same as useState in React JS.

Why use ‘Signals’ instead of State?

// Using signal in Solid JS
import { createSignal } from 'solid-js';

function Counter() {
  const [getCount, setCount] = createSignal(0);

  function increment() {
    setCount(getCount() + 1);
  }

  return (
    <div>
      <p>Count: {getCount()}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
// Using signal in Qwik
import { component$, useSignal } from '@builder.io/qwik';

export default component$(() => {
  const count = useSignal(0);

  return (
    <button onClick$={() => count.value++}>
      Increment {count.value}
    </button>
  );
});

Let’s take a look at the Solid Js code:

  • createSignal(): allocates the StateStorage and initializes it to 0.

  • getCount: a reference to the store that you can pass around.

  • getCount(): says retrieve the state value.

While in Qwik’s code, the getter/setter has been replaced with a single object with a .value property (which represents the getter/setter). While the syntax is different, the inner workings remain the same.

The issue with useState is returning the value rather than a getter function. So, why return a getter function would be better? Because by returning the getter, you can separate the passing of the state reference from a reading of the state value. The giving of state value does not give any information about where the value is actually used. When the value is changed by invoking the setter function, It will trigger a re-render of the whole VDOM tree. On the other hand, by returning state reference, Signals will re-render the components that consume the state value.

Here is a quick example using Jotai and Jotai Signal to show the differences when updating the state using useState and signal. The source code can be found at here.

Thank you for your reading 🙏

References

  1. https://www.builder.io/blog/usesignal-is-the-future-of-web-frameworks