Reusable, Extensible and Testable State Logic with Reactive Programming.
Dave Lai
Posted on November 29, 2024
State in UI Components
When we start introducing state into a UI component it is often tempting to do something like this:
Simple Counter Example in Svelte:
<script>
let count = $state(0);
</script>
<button onclick={() => count++}>
clicks: {count}
</button>
Problem
We use Svelte here but same the issue can apply in any UI framework.
Off the bat we have tightly coupled our state logic with the component - the increment functionality is coded right in the template.
With this set up we can not reuse the counter logic in:
- other UI components
- other business logic that requires a counter
- other UI frameworks
We also cannot test the counter logic without rendering the component. If the component has other functionality coupled with it, isolating the counter logic would not be possible.
Solution
Separate state logic from the UI component so it can be implemented and tested independently. This will make the logic more reusable and UI components only need to listen for state changes and render. Consider the following:
<script>
import { RxCounter } from './RxCounter';
const [count, { increment }] = RxCounter();
</script>
<button onclick={increment}>
Count: {$count}
</button>
See full example on StackBlitz
If you compare above with our original example, all the logic for the counter is now encapsulated in RxCounter
(we will show the implementation later).
count
is an RxJS Observable that emits the new count state. increment
is an action method the UI can call to invoke state changes.
Svelte has a nice built in way of subscribing to observables in the template as seen with the $count
template variable. Subscribing to an observable in any UI framework is not terribly difficult, and many frameworks have APIs to help accomplish this.
Implementing RxCounter
Information and Disclaimer: We will make use of Reactables API
created by the author. It is a state management solution that leverages RxJS
to make reactive programming easier.
Get the Reactables Core Package and create RxCounter
.
npm i @reactables/core
import { RxBuilder } from '@reactables/core';
export const RxCounter = () =>
RxBuilder({
initialState: 0,
reducers: {
increment: (count) => count + 1,
},
});
RxBuilder
returns a Reactable
.
A Reactable
is a tuple with its first item being an RxJS Observable emitting state changes and second item being a dictionary of action methods for triggering state updates.
The state is reactive, meaning the state responds to changes via its reducer functions. When an increment
action triggered by the UI is received, the reactable reacts and its observable emits the new state.
Note RxCounter
is now completely decoupled from the view layer and can be used in any UI framework!
Testing the Counter
To test a Reactable
, we subscribe to its state observable and invoke its action methods to test its behaviour. We can assert the observable's emitted values matches the desired behaviour.
This can be done with RxJS’s built in Marble Testing.
import { RxCounter } from './RxCounter';
import { Subscription } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
describe('RxCounter', () => {
let testScheduler: TestScheduler;
let subscription: Subscription;
beforeEach(() => {
testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
});
afterEach(() => {
subscription?.unsubscribe();
});
it('should increment', () => {
testScheduler.run(({ expectObservable, cold }) => {
// Create Counter Reactable
const [count$, { increment }] = RxCounter();
// Call actions
subscription = cold('--b', {
b: increment,
}).subscribe((action) => action());
// Assertions
expectObservable(count$).toBe('a-b', {
a: 0,
b: 1,
});
});
});
});
Extending the Counter
With the state logic isolated from the view, we can also extend the functionality of RxCounter
and create a RxDoubleCounter
that has the ability to double the count.
import { RxBuilder } from '@reactables/core';
export const RxCounter = (options) =>
RxBuilder({
initialState: 0,
reducers: {
increment: (count) => count + 1,
...options?.reducers,
},
});
export const RxDoubleCounter = () =>
RxCounter({
reducers: { doubleCount: (count) => count * 2 },
});
See full example on StackBlitz
Conclusion
Implementing state logic directly in UI components makes the logic harder to reuse and test.
We can program the state logic reactively with Reactables and test it in isolation. This produces a unit of reactive state logic that is highly reusable in both the view and logic layer.
We did a simple counter example here, but Reactables are extensible and composable for much more complex state management scenarios (i.e data fetching, forms etc...). Check out the docs to learn more!
Posted on November 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.