DEV Community

Cover image for Using SignalDB with React: A complete guide
Megan Lee for LogRocket

Posted on • Originally published at blog.logrocket.com

Using SignalDB with React: A complete guide

Written by Antonello Zanini
✏️

With its first commit in July 2023, SignalDB is a relatively new client-side JavaScript database that promises to revolutionize data management through its reactive approach to data changes.

SignalDB relies on signals like SolidJS to enable automatic data synchronization between your components and a local in-memory or persistent database. That makes it the perfect solution for efficient state management in React.

In this guide, you will discover what SignalDB is, how it works, what its benefits are when integrated into a React application, and how it compares to MongoDB.

High-level overview of reactive databases

A reactive database is a type of database system based on The Reactive Principles, which revolve around the idea of automatically responding to data changes by propagating them throughout the entire application. In the context of databases, this means updating, adding, or removing data triggers immediate and automatic updates to connected systems.

To better understand what this technology brings, consider a common scenario of a frontend application, such as a React SPA.

If you use traditional databases to store data, you must manually manage data changes and ensure that the user interface reflects the latest updates. On the other hand, if you opt for a reactive JavaScript database that stores data locally, the propagation of data updates is handled automatically for you.

In other words, the reactive database technology takes care of propagating data updates to your React components in real time. This greatly reduces the developer's burden while making it easier to achieve a seamless UX. As a result, reactive databases are very popular in the frontend.

Reactive databases go beyond mere data storage and aim to revolutionize web development by eliminating the need for complex data update logic. In the realm of frontend JavaScript apps, that leads to more efficient, dynamic, and interactive applications that provide a high-level UX.

What is SignalDB?

SignalDB is a reactive, signal-based, client-side JavaScript database designed for modern web apps. It offers a powerful MongoDB-like interface for data handling through an intuitive API with first-class TypeScript support. This database technology is available via the signaldb npm package.

SignalDB prioritizes a reactive approach to data management, ensuring real-time synchronization and updates via signals. A signal — a core concept of functional reactive programming — refers to a stream of data that represents values that change over time.

In essence, a signal is an object that contains a value. When this value changes, the frontend components that access this value are automatically updated. SignalDB uses signals to handle reactivity, seamlessly synchronizing and reacting to data changes in the database.

At the same time, keep in mind that SignalDB is just a database system. That means it is neutral to any particular signal library, supporting many of them through specific reactivity adapters. As of this writing, the reactive JavaScript database solution provides built-in reactivity adapters for these packages and technologies:

  • @preact/signals-core
  • @reactively/core
  • Angular
  • @maverick-js/signals
  • Meteor Tracker
  • MobX
  • @vobyjs/oby
  • S.js
  • sinuous
  • Solid.js
  • usignal
  • Vue.js

Check out the documentation to find out all the supported adapters and how to use them.

SignalDB is also versatile when it comes to data persistence. It allows you to store data through a JSON interface in different storage providers, including localStorage, RxDB, Firebase, Appwrite, the filesystem, and others.

This flexibility enables you to choose the most suitable storage approach, supporting both temporary session storage and more permanent data retention needs.

SignalDB's client-side architecture sets it apart from traditional databases, providing immediate access to data without server-side latency. That is a key requirement for reactivity, which makes it great for applications with high performance and real-time interaction demands.

In addition, SignalDB’s framework-agnostic nature means it can be used in React, Angular, Vue.js, or any other JavaScript framework.

How SignalDB works

Just as in MongoDB, SignalDB stores data in collections. A Collection is an object designed to manage and manipulate collections of data documents in memory or on disk.

Collections are schema-less, which means that you do not need to define a schema for your data before storing it. However, it is recommended to define a TypeScript interface for documents in the collection to ensure type safety when working with the data.

The way SignalDB handles data storage and reactivity for these collections depends on the approach to storage and the reactive library chosen, respectively.

This is how you can define a collection in SignalDB:

import { Collection } from "signaldb"

// create the "posts" collection
const posts = new Collection()
Enter fullscreen mode Exit fullscreen mode

By default, data is stored in memory. If you want to persist it, you must specify a data persistence adapter as explained in the documentation.

To insert data into a collection, use the insert() method:

// add a new post object to the "posts" collection
const id = posts.insert({
  id: 1498,
  url: "https://blog.logrocket.com/express-js-adoption-guide/",
  title: "Express.js adoption guide: Overview, examples, and alternatives",
  author: "Antonello Zanini",
  coverImage: "https://blog.logrocket.com/wp-content/uploads/2023/12/Express-js-adoption-guide.png",
  content: "Express.js is a Node.js framework for creating maintainable and fast backend web applications in JavaScript. In the fast-paced world of web development...",
  shares: 19226,
})
Enter fullscreen mode Exit fullscreen mode

To update data in a collection, use the updateOne() or updateMany() method:

// update the title of the post with id=1498
posts.updateOne({ id: 1498 }, {
  $set: { title: "The definitive guide to Express.js" },
})

// change the author of all posts written by Antonello Zanini
posts.updateMany({ author: "Antonello Zanini" }, {
  $set: { author: "LogRocket Team" },
})
Enter fullscreen mode Exit fullscreen mode

To provide modifiers that are very similar to those in MongoDB, SignalDB relies on the mingo library.

Similarly, you can delete some documents from a collection using the removeOne() or removeMany() method:

// update the title of the post with id=1498
collection.removeOne({ id: 1498 })

// remove all posts written by Antonello Zanini
collection.removeMany({ author: "Antonello Zanini" })
Enter fullscreen mode Exit fullscreen mode

The Collection class also exposes two methods for querying data, namely find() and findOne(). findOne() returns the first found document, while find() returns a cursor. Both methods accept two optional parameters:

  • selector: A function to filter items in the collection that supports MongoDB-like selectors as specified in the mingo library. These include $gt, $gte, $in, $lt, $lte, $ne, $nin, and others
  • options: Options to control sorting, projection, skipping, or limiting data

See find() in action in the example below:

// find the first 10 posts written by Antonello Zanini
// that where shared more than 1000 times
const cursor = posts.find(
  {
    author: "Antonello Zanini",
    score: { $gte: 1000 },
  },
  {
    limit: 10,
  },
)
Enter fullscreen mode Exit fullscreen mode

Benefits of using SignalDB in React

Now you know SignalDB and how it works, but what advantages does it bring to a real React application? Let’s discuss some of its benefits in these next few sections.

Easier state management

SignalDB simplifies state handling in React because of its reactive approach to data management.

The client-side nature of SignalDB ensures instantaneous automatic updates, eliminating the need to make AJAX API calls to the backend and wait for a response to show updated data. This also removes the need for state propagation in the component tree.

Similar to Redux, SignalDB stores the state in a centralized store. That means any components, functions, or utilities can retrieve and update the state data, which is easy thanks to the MongoDB-like intuitive API offered by SignalDB.

Combining these advanced querying capabilities with its reactive approach to data synchronization allows SignalDB to streamline state management in React components.

Promotes optimistic UI and offline-first design

An optimistic UI means that the UI is immediately updated in response to certain user actions before actually receiving the response from the server. This provides a smoother and more reactive experience as the user does not have to wait for server confirmation.

SignalDB promotes an optimistic UI thanks to its reactive nature, enabling your React application to display changes in the UI as soon as the underlying data is modified. That implies you can guarantee immediate visual updates, no matter how much time the server takes to respond.

As a result, SignalDB also excels in offline scenarios, ensuring interactivity even with limited Internet connectivity. It handles offline data changes gracefully, synchronizing them automatically when connectivity is restored.

These SignalDB features set the stage for offline-first design, allowing your React application to remain functional in various states of connectivity.

Reduced re-renders

When using a React Context for global state management, all consumers of a given context will re-render whenever its context value changes. As you can imagine, this can easily cause performance bottlenecks in your React web app, especially in highly interactive applications.

Now, suppose you store your state in SignalDB. React will be able to jump immediately to the components in the tree that need an update and re-render only those, achieving much better performance.

SignalDB makes this possible by using signals to keep the database synchronized. Signals help React re-render components in a smarter way after an update.

SignalDB in React: Pros and cons

To be fair, it’s also important to consider the potential cons of SignalDB. Let’s quickly summarize the benefits and challenges associated with using SignalDB with React.

👍 Pros:

  • Supports optimistic UI and offline-first design
  • Provides fast UI updates in the components
  • Automatic data update propagation with optimized re-rendering logic
  • Scalable solution for global state management

👎 Cons:

  • Automatic updates make debugging more difficult
  • Still relatively new, so there’s not much documentation available

SignalDB vs. MongoDB for data management in React

When it comes to data storage, SignalDB offers a similar approach to MongoDB. Considering the popularity of the MERN stack, why should you even contemplate using SignalDB in your React application?

Let's compare SignalDB and MongoDB and answer that question:

  • Nature: MongoDB is a server-side technology, whereas SignalDB is a client-side technology. Thus, while MongoDB should run on a dedicated server, SignalDB can be installed as a dependency of your React project
  • Performance: As database technologies, SignalDB and MongoDB offer similar performance. The main difference is that the former runs on a client, while the latter runs on a server. Servers are generally faster than clients as all their resources are dedicated to a specific service. At the same time, React is a frontend technology and does not run on the server. That means that whenever you need to access or write MongoDB data, you need to make an API call to a backend server such as Express.js that will contact MongoDB for you. This turnaround adds a significant overhead, which makes using MongoDB in React inherently slower than SignalDB
  • Querying: mingo empowers SignalDB to deliver a MongoDB-like data querying experience. While MongoDB may still offer more features such as aggregations, the two querying systems are entirely comparable
  • Persistence: Just as MongoDB supports different storage engines, SignalDB supports different data persistence mechanisms. Again, the two database technologies follow a similar approach. The major difference is that MongoDB is a persistent database that also offers an in-memory option, while SignalDB is an in-memory database that also offers options for persistence.

What is truly important to understand here is that MongoDB and SignalDB are not mutually exclusive technologies. Quite the opposite!

A React application can use SignalDB for storing data locally and implement optimistic UI and offline-first design. Simultaneously, it can rely on MongoDB via a backend to persist data remotely.

Conclusion

In this article, you learned that SignalDB is a reactive JavaScript database that helps you build interactive React applications with an offline-first design and optimistic UI. These are just some of the great benefits introduced by this new database technology.

With its MongoDB-like API, SignalDB makes it very easy to retrieve, modify, and delete data. It also uses signals to allow data to be updated without triggering many re-reads in the component tree. That makes it a great tool for efficient state management in React.


Get set up with LogRocket's modern React error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.

NPM:

$ npm i --save logrocket 

// Code:

import LogRocket from 'logrocket'; 
LogRocket.init('app/id');
Enter fullscreen mode Exit fullscreen mode

Script Tag:

Add to your HTML:

<script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
<script>window.LogRocket && window.LogRocket.init('app/id');</script>
Enter fullscreen mode Exit fullscreen mode

3.(Optional) Install plugins for deeper integrations with your stack:

  • Redux middleware
  • ngrx middleware
  • Vuex plugin

Get started now

Top comments (0)