Unlocking React ’s Potential with Signals: A Step-by-Step Guide to Implementing Computed(Part 2)

Furkan Kaynak
3 min readNov 10, 2023

--

What is Computed signals?

In our second blog post of the Signal series, we’ll explore computed signals in React. Computed signals are an advanced feature that allows you to derive and compute values based on the state changes of your application. These signals enable efficient and dynamic calculations, enhancing the flexibility and functionality of your React components. Stay tuned as we break down the simplicity and power behind computed signals, providing a practical guide on leveraging them for effective state management in your projects.

Let’s Rock and Roll

Similar to our previous implementation, computed signals provide a streamlined and component-like approach to handle derived states in your React applications.

A computed state is a dynamically derived state value calculated based on Signal. It represents data transformations or combinations that are automatically updated when its dependencies change. In contrast, the Signal class focuses on managing and propagating changes in a single state, while the Computed class extends this functionality to handle the dynamic computation of state values based on dependencies. The key distinction lies in the Computed class's ability to automate the calculation of state values, enabling reactive updates in response to changes in the underlying data.

In exploring computed signals, we delve into two implementation approaches: one with dependencies and the other without dependencies. Let’s commence our journey by examining the version with dependencies.

Implementing Computed Signals with Dependencies

1. Creating the Computed Class:

We extend the base Signal class to create Computed, focusing on automating the calculation of state values.

class Computed extends Signal {
constructor(computedFn, deps = []) {
super();
this._computedFn = computedFn;

// Subscribe to dependencies, triggering updates on change
deps.forEach((dependency) => {
dependency.subscribe(this.updater);
});
}

2. Setting Up Dependencies:

The Computed class accepts a computation function (computedFn) and an array of dependencies (deps). It subscribes to each dependency, ensuring that any change triggers an automatic recalculation.

3. Updating Computed Value:

The updater function responds to changes in dependencies by recalculating the computed value and notifying listeners.

  updater = () => {
this.setComputedValue();
this.notifyListeners();
};

4. Accessing the Computed Value:

The value getter retrieves the computed value. It invokes the computation function and ensures the value is always up-to-date.

  
setComputedValue = () => {
this._value = this._computedFn();
};

get value() {
this.setComputedValue();
return this._value;
}

5. Complete Computed Class Implementation:

class Computed extends Signal {
constructor(computedFn, deps = []) {
super();
this._computedFn = computedFn;

deps.forEach((dependency) => {
dependency.subscribe(this.updater);
});
}

setComputedValue = () => {
this._value = this._computedFn();
};

updater = () => {
this.setComputedValue();
this.notifyListeners();
};

get value() {
this.setComputedValue();
return this._value;
}
}

export const computed = (fn, deps) => new Computed(fn, deps);

Putting it into Action:

Now, let’s consider a real-world scenario where a computed signal calculates the total price based on the quantity and unit price:

In this example, changes in quantitySignal or unitPriceSignal will automatically update totalPriceSignal, showcasing the power and efficiency of computed signals.

const quantitySignal = signal(3);
const unitPriceSignal = signal(10);

// Creating a computed signal for total price
const totalPriceSignal = computed(() => quantitySignal.value * unitPriceSignal.value, [quantitySignal, unitPriceSignal]);

This implementation empowers developers to create reactive, dependent state values in a concise and maintainable manner, enhancing the flexibility of state management in React applications.

You can test full example of Signal implementation on :

To be continued with Part-3: Implementing Computed Signals without Dependencies

Part 1 : Unlocking React’s Potential with Signals: A Step-by-Step Guide to Implementing Signals

Please Follow me for more interesting content

--

--

Furkan Kaynak

Senior Full Stack Developer @obsstech | Passionate about JavaScript, ReactJS, NodeJS, and AWS