Building a Simple Reactive System with JavaScript

Aaron Billings
2 min readNov 22, 2023

Reactive programming is a paradigm that allows developers to model data and its changes in a declarative manner. An example library that uses this paradigm is RxJS. However you can use this paradigm in Angular, React or other libraries.

In this article, we’ll explore a concise JavaScript code snippet that implements a basic reactive system.

This system consists of two main functions: `createSignal` for managing reactive state, and `createEffect` for handling side effects.

Let’s jump into it!

Understanding the Code

const context = [];

export function createSignal(value) {
const subscriptions = new Set();

const read = () => {
const observer = context[context.length - 1]
if (observer) subscriptions.add(observer);
return value;
}

const write = (newValue) => {
value = newValue;
for (const observer of subscriptions) {
observer.execute()
}
}

return [read, write];
}

export function createEffect(fn) {
const effect = {
execute() {
context.push(effect);
fn();
context.pop();
}
}

effect.execute();
}
  • The `createSignal` function initializes a reactive signal with an initial value.
  • The `read` function is used to read the current value of the signal. It also adds the current observer to the list of subscriptions.
  • The `write` function updates the signal’s value and notifies all subscribed observers by calling their `execute` method.
  • The `createEffect` function creates an observer (effect) that runs the provided function when executed. It ensures that during the execution, it is the current observer in the context.

Usage Example

// Importing the reactive functions
import { createSignal, createEffect } from "./reactive";

// Creating a reactive signal 'count' with initial value 0
const [count, setCount] = createSignal(0);

// Creating an effect that logs the current count
createEffect(() => {
console.log(count());
}); // Output: 0

// Updating the count and triggering the effect
setCount(10); // Output: 10

This simple reactive system allows developers to create reactive signals and effects, providing a foundation for building more complex reactive applications.

Understanding the principles behind this implementation can be a valuable step toward grasping the concepts of reactive programming in JavaScript.

--

--

Aaron Billings

Full Stack developer that follows the ABCs (Always Be Coding). If I’m not coding you can find me playing video games, or spending time with family.