Home Web Development Redux Made Easy with Rematch

Redux Made Easy with Rematch

By Sergio Moreno
books-svg-icon Book
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Why Redux? An Introduction to Redux Architecture
About this book
Rematch is Redux best practices without the boilerplate. This book is an easy-to-read guide for anyone who wants to get started with Redux, and for those who are already using it and want to improve their codebase. Complete with hands-on tutorials, projects, and self-assessment questions, this easy-to-follow guide will take you from the simplest through to the most complex layers of Rematch. You’ll learn how to migrate from Redux, and write plugins to set up a fully tested store by integrating it with vanilla JavaScript, React, and React Native. You'll then build a real-world application from scratch with the power of Rematch and its plugins. As you advance, you’ll see how plugins extend Rematch functionalities, understanding how they work and help to create a maintainable project. Finally, you'll analyze the future of Rematch and how the frontend ecosystem is becoming easier to use and maintain with alternatives to Redux. By the end of this book, you'll be able to have total control of the application state and use Rematch to manage its scalability with simplicity.
Publication date:
August 2021
Publisher
Packt
Pages
286
ISBN
9781801076210

 

Chapter 1: Why Redux? An Introduction to Redux Architecture

Redux is a consolidated state management solution used by millions of websites, downloaded 3 million times per week. Overall, it's a great solution for a complex problem, but it was created with some limitations that Rematch aims to solve with best practices.

In this book, we'll analyze the weakest points of Redux and how Rematch solves them with a small wrapper in less than 2 KB. We'll move from the most basic example of a to-do task application to an Amazon clone website built with React and latest web technologies trends. We'll also create a mobile application with React Native and Rematch, introduce testing coverage, and, of course, explore TypeScript and Rematch plugins. By the end of this book, you'll be able to create any application or migrate an existing one to Rematch.

In this chapter, we'll learn why Redux was created and what problem it is designed to solve. Also, we'll learn how it works internally, and we'll get acquainted with some Redux terminology.

In this chapter, we will cover the following topics:

  • Why Redux?
  • What was there before Redux?
  • How does Redux work?

By the end of this chapter, you will know the story behind Redux, how it works internally, and what was the cause of its creation. Of course, you will also learn practically all the most important terminology of Redux and use it in the next chapters.

 

Technical requirements

To follow along with this chapter, all you will need is a basic knowledge of ES6 JavaScript.

 

Why Redux?

To get started with this book, it's interesting to know what Redux does and what problem it's designed to solve.

In 2015, Redux was created by Dan Abramov, who began writing the first Redux implementation while preparing for a conference talk at React Europe, and Andrew Clark. Redux is a predictable state container for JavaScript applications; in other words, it is a utility tool to manage global states, which means data that is reachable across many parts of your application.

Where I used to work, we always asked the same question before starting a project: do we really need Redux? The problem we found is that when your application gets more complex, with more components that need to pass props down from a parent component to child components, the more complex the project becomes to read and improve. In short, it becomes unmaintainable.

This is an example of a common architecture of a basic application that passes down props from a parent component to child components:

Figure 1.1 – React architecture without Redux

That's where Redux joins the game. Redux eases these complexities, providing patterns and tools that make it easier to understand when, where, why, and how the state will be updated, and how your application logic will behave when those changes occur.

Redux will help when we need to do the following tasks:

  • Manage large amounts of application state that are needed in many places.
  • Manage business logic that is complex to update.
  • Create an app that will be maintained by many people.

A year after releasing React, Facebook published the Flux architecture on social media. Flux is more of a pattern than a framework; it eschews Model-View-Controller (MVC) in favor of a unidirectional data flow. When a user interacts with the user interface, the user interface propagates an action through a singleton dispatcher to many stores that hold the application's data, which updates all of the user interfaces that are affected. Flux architecture became really popular, and so many implementations appeared, too, but the most popular was Redux; the adoption of Redux was quickly adopted by the React community, and it soon became common to teach the use of React and Redux together.

Now that we know why Redux is interesting for our projects and why it was created, we should look at what frontend technologies for state management existed before Redux entered the game.

 

What was there before Redux?

In 2011, Facebook had a big issue with its notification system; the problem was called Zombie Notifications. Users received chat notifications, but when they clicked on them, there would be no new messages waiting for them. The Facebook team was getting a lot of complaints about this issue, and after a lot of research, they found the problem: the entire architecture was weak and had been since its creation.

Facebook was using the MVC architecture at the time, which became increasingly unstable as the application grew more and more complex. Here's an example of a common MVC architecture:

Figure 1.2 – MVC architecture

Basically, the number of models, controllers, and views that shaped Facebook became unmanageable to maintain. That's why newer frameworks appeared in the frontend ecosystem, one of which was Backbone.js.

Backbone.js was one of the first popular MVC frameworks that went viral around 2015. It acts as a smart wrapper around JavaScript objects and arrays and includes a small pub-sub events system built into it. Pub-sub is a publisher-subscriber relationship where the publisher sends a message to a topic and it is immediately received by the subscriber. All models and collections automatically trigger events as data is changed.

Here is an example of Backbone.js architecture:

Figure 1.3 – Backbone.js architecture

We can compare Backbone.js with the MVC architecture in Figure 1.2 and see how much easier Backbone.js was compared to an MVC architecture, but there was still work ahead to improve even more the state management solutions.

In 2014, Flux was adopted early by many people and this new method of state management was approved by developers. One of the main concepts of Flux is that all data must flow in only one direction. When the data flow is always in the same direction, everything is super predictable.

As we saw in Figure 1.2, some views and models have arrows running in both directions, so the data flow is bidirectional. With Flux, the MVC diagram is reconsidered, as shown in Figure 1.4:

Figure 1.4 – Flux architecture

Let's briefly explain what the elements in each box mean.

Flux Actions

Actions are descriptions of the ways users can interact with the app. Basically, they are JavaScript objects, whose only requirement is to contain a required type field, although they do contain extra data used to fill the store.

Here is an example of a Flux action with the required type field and a payload object:

{
  "type": "ADD_TODO_ITEM",
  "payload": {
    "taskId": 1,
    "task": "Some task name"
  }
}

We use the type field to define what kind of change will be made to the app state, and payload is used for passing data to the store.

Flux Dispatcher

The Dispatcher function receives an action as an argument and forwards it to each of the application's stores. We have to remember that any Flux application with a solid pattern must only contain one dispatcher method.

To make it clear, we could say the dispatcher method is like a central interface between actions and stores. Basically, it is the magic wand that orchestrates actions and sends them directly to the store.

Here is an example of a Flux Dispatcher:

const countDispatcher = new CountDispatcher();
let countStore = {count:0}
countDispatcher.dispatch({ action: 'incrementCount' })
console.log(countStore)
// {count: 1}

This code is just an example of how a Flux dispatch function could be executed; the most common way is passing an object with the type that must match the reducer name. This is why we must think about dispatching actions such as triggering events – something happened, and we want the store to know about it.

Flux Stores

Stores contain the application state and logic. They are similar to a model in the MVC architecture.

A store registers itself with the dispatcher and provides it with a callback. This callback receives the action as a parameter, the store is subscribed to read any action that comes, and decides accordingly how to interpret that action. After the stores are updated, they broadcast an event declaring that their state has changed. In that way, the user interfaces can query the new state and repaint the screen correctly.

Basically, we have to understand that in order to modify our stores, we'll need to "dispatch" actions. Since all stores receive actions, a store will determine whether or not to modify its state upon receiving an action by looking at that action's type.

Views

Views (also called user interfaces) are what the user can see and interact with. They are the interfaces for displaying the data coming from our stores, as well as for sending actions back to the stores through the Dispatcher. Flux and Redux were designed to work with any frontend framework because there are bindings. A software binding refers to a mapping of one thing to another; it's like a wrapper to resolve the complexities of other libraries, but they were mainly designed to work with React.

For React there is a library called react-redux, a library for which you need to learn just one method for now: connect(). To be brief, because we'll explain this in detail in Chapter 5, React with Rematch – The Best Couple – Part I, connect() maps our Redux state to props on our React component. With this library, it becomes easier to integrate Redux into our React projects.

The following diagram depicts how React handles Redux subscriptions:

Figure 1.5 – React UI architecture with Redux

We can see the common architecture of Redux, but with the addition of a section called Link – this is where the react-redux connect() function makes the connection between React and Redux.

In this section, we learned how frontend technologies regarding state management evolved. We also learned how Flux works and why it was created, covering the main concepts to continue our journey with Redux. Now we are going to introduce and compare the main differences between Flux architecture and the refined way of Redux.

 

How does Redux work?

Flux is a generalized pattern of doing things, a reusable solution to a frequent problem in software architecture within a given situation. Redux is one of the frameworks that took this pattern and tweaked it to solve even more problems.

Redux and Flux both share the concern that you must concentrate your store update logic somewhere. In Flux, stores could be a good place to store the data and its logic, but in Redux, we use reducers because Redux only has a single store. This means that we only have one way to communicate with that source of truth, through actions that trigger reducers that update the store.

As we did with the Flux pattern, to help us compare the differences, let's see a diagram of the Redux architecture:

Figure 1.6 – Redux architecture

With Redux, the whole application state is placed within a centralized store that acts as the application's single source of truth. Also, the store becomes simpler because then it's only responsible for containing the state and is no longer in charge of determining how to adjust its state in response to actions – that logic is assigned to reducers.

Actions follow the same pattern in Flux as in Redux, which means we can now jump straight to reducers and stores.

Reducers

Reducers are just pure functions. Pure functions, by definition, are functions where the return value is always determined by its input values, which means that they are really predictable and testable. To clarify this, a pure function will never be a function with side effects. Side effects are usually AJAX requests, random numbers, mutations... because they introduce newer data that doesn't depend directly on its input values.

Reducers are simply functions that accept the current state as the first argument and the second argument as a given action. The output will be either the unmodified state or a new, edited copy of the state.

Another difference with Flux is that Redux assumes your state is immutable; that means you can't mutate your data. Reducers must always return the entire state (that means a new object reference), which is easy with the new object/array spread operator, a new proposal in JavaScript. This allows us to use the spread () operator to copy enumerable properties from one object to another in a simpler way.

Here's an example of a Redux reducer in code:

const todoAppReducer = (state = { tasks: [] }, action) => {
  switch (action.type) {
    case 'ADD_TODO_TASK':
      return {
        ...state,
        tasks: [
          ...state.tasks,
          action.payload
        ]
      }
    default: return state
  }
}

This reducer will read from an action argument with a payload, which is the new task that will be added to current state tasks. We use the spread operator to easily merge the current state with the new state.

Stores

Redux stores employ shallow equality checking, which simply entails checking that two different variables reference the same object. A shallow equality check that comes quickly to our minds is a simple a === b; therefore, they are immutable by default, which means you can't change the state directly. You must use reducers to make copies of existing objects/arrays, and modify the copies if needed, to finally return the new reference.

The main difference between Redux and Flux is that Redux only includes a single store per application instead of multiple stores, as Flux does. Having a single store makes persisting and updating the user interface simpler and, of course, simplifies the subscription logic.

This doesn't mean that every piece of state in your application must be placed in a Redux store. You should decide whether a piece of state belongs in Redux or your user interface components. For example, if we build a little component with some internal configuration that just belongs to that component, it isn't a good practice to introduce that state into Redux – just keep it simple using the local state.

We already mentioned that data must flow in only one direction, which perfectly describes the steps to update our application UI.

When our application is rendered for the first time, the following occurs:

  1. A store is created using a root reducer function.
  2. The store calls the root reducer once and saves the return value as its initial state.
  3. When the user interface is first rendered, our user interface will access our data inside the store and also subscribe to any future store updates to know whether the state has changed.

What about when we update something in the application? The application code must dispatch an action to the Redux store like so:

store.dispatch({ type: "counter/increment" })

When the store receives the emitted action, the following occurs:

  1. The store runs the reducer function again with the previous state and the current action and saves the return value as the new state.
  2. The store notifies all parts of the user interface that subscribed previously.
  3. Each component that has subscribed forces a re-render with the new data.

Unidirectional flow is the concept key that Redux offers against other state management solutions, it's predictable by default. Because you can't ever mutate the application state, all the changes in our state are done through reducers, which are invoked through actions, creating a predictable state, since the consequence of an action will result in a concrete state:

Figure 1.7 – Redux unidirectional data flow

Creating a state that is predictable means that by using Redux, we will know what every single action in our application will do and how the state will change when this action is received.

 

Summary

In this chapter, we have learned the main differences between Flux and Redux and understood the key concepts needed to start a simple application with Redux. Understanding these concepts and terminology will allow you to follow along with the next chapters related to Rematch without any problems.

In the next chapter, we will learn why Rematch was created on top of Redux, and what problems it tries to solve.

About the Author
  • Sergio Moreno

    Sergio Moreno is a front-end developer with more than 4 years of experience really focused in the analysis, design, development and building large-scale applications. Formerly worked at Allfunds, the world's largest fund distribution network, he led the front-end team to build a full new suite of products for the new Digital section of Allfunds. He entered the open-source world in 2019 where's contributed to big companies like Google, Facebook, Airbnb, or Pinterest and much more. In 2020 focused his contributions to Rematch, where he released the v2 version with a full rewrite of the codebase and a full compatibility with Typescript and so many improvements like reducing the bundlesize in some cases by 110%, and Lingui, an amazing internationalization library, who helped to release the v3 version. In 2021, joined Flowable as Product Engineer, a compact and highly efficient workflow and business process management platform for developers, system admins and business users.

    Browse publications by this author
Redux Made Easy with Rematch
Unlock this book and the full library FREE for 7 days
Start now