Quick overview of signals in JavaScript

2 min read

singals 為 fine-grained reactivity 的一種實作,這裡先簡單分成三個部分:

simple model of fine-grained reactivity

從 solid 及 vue 的 api 可以看到類似的概念

import {
  createMemo,
  createSignal,
  createEffect,
} from 'solid-js';
 
// observable state
const [count, setCount] = createSignal(0);
 
// derivation
const double = createMemo(() => {
  // read a value
  return count() * 2
});
 
// effect
createEffect(() => {
  // read a value
  console.log(count());
});
 
// set a value
setCount(5);

observable state 實作上,常見包含 value, getter, setter

derivations, effects 實作上,需要考慮:

fine-grained-reactivity-unnecessary-calculation

未來 signals 也有機會標準化,這些複雜的實作細節,如果在 runtime layer 都處理好那是再好不過

// observable state
const count = new Signal.State(0);
 
// derivations
const double = new Signal.Computed(() => counter.get() * 2);
 
// effect
effect(() => {
  console.log(count.get());
});
 
// set value
count.set(counter.get() + 1);

Reference