DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Simple State Management with RxJS β€” a To-do List example
Duc Le
Duc Le

Posted on

Simple State Management with RxJS β€” a To-do List example

What is RxJS ?

RxJS is a Reactive Extensions Library for JavaScript which is getting very popular.

According to Wikipedia, Reactive Programming is a declarative programming paradigm concerned with data streams and the propagation of change.

I will cover some basics before moving on:

  • Observable: represents the idea of an invokable collection of future values or events.
  • Observer: is a collection of callbacks that knows how to listen to values delivered by the Observable.
  • Subscription: represents the execution of an Observable, is primarily useful for cancelling the execution.

Setting up the project

You can use basically any UI Framework or library out there, even with vanilla JS. In this article, I will go with SolidJS ( you can find it very similar to React )

npx degit solidjs/templates/ts my-app

Enter fullscreen mode Exit fullscreen mode

This will generate a new Solid app with TypeScript, next, just add the RxJS library

yarn add rxjs
yarn dev
Enter fullscreen mode Exit fullscreen mode

Setup store

In the src folder, let’s create the state.ts file ( you can name it store or whatever ) then create the initialState and subject

Image description

Subscriptions

An RxJS Subject is the only way of multicasting a value or event to multiple Observers. In this example, we’ll be subscribing our different setter functions to our RxJS Subject so that when it receives any data, it forwards that data to every state associated with our setter function ( if you familiar with React, then just pass a setState to it )

Then, we will subscribe to it

Image description

Next, we will create an init method to initialize the state

Image description

The next method is used to push a value to the subject, when we call the next method with a value as its parameter, that value is casted to all Observers subscribed to the Subject.

Add, delete and modify the state

Nothing much to say about this, just like every other to-do list example, we need multiple method to modify the state that holds the tasks

Image description

This is a complete version of our app, you can add more methods if you want to fulfill you desire. The final product might looks like this, depend on your styling :

Image description

Hope this tutorial can help you understand basics of RxJS and its usage. You can find the source code here

References:

https://rxjs.dev/
https://en.wikipedia.org/wiki/Reactive_programming
https://blog.logrocket.com/rxjs-react-hooks-for-state-management/

Top comments (0)

Let's team up together 🀝

We're Hiring

We're hiring for a Senior Full Stack Engineer to join the DEV team. Want the deets? Head here to learn more about who we're looking for.