Search icon CANCEL
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
$9.99 | ALL EBOOKS & VIDEOS
Save more on purchases! Buy 2 and save 10%, Buy 3 and save 15%, Buy 5 and save 20%
Redux Made Easy with Rematch
Redux Made Easy with Rematch

Redux Made Easy with Rematch: Reduce Redux boilerplate and apply best practices with Rematch

By Sergio Moreno
$25.99 $9.99
Book Aug 2021 286 pages 1st Edition
eBook
$25.99 $9.99
Print
$32.99
Subscription
$15.99 Monthly
eBook
$25.99 $9.99
Print
$32.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Redux Made Easy with Rematch

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get to grips with the capabilities of Rematch quickly as you build applications
  • Learn to use Rematch and its plugins to simplify everyday tasks
  • Take total control of the application state and manage its scalability using Rematch

Description

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.

What you will learn

Understand the principal concepts of Flux and Redux Find out what the main problems are that Rematch solves Become familiar with the Rematch ecosystem Develop an application using Rematch and React together Write unit and integration tests to get 100% test coverage of your programs with Rematch Create a React Native app with Rematch and Expo Persist data with redux-persist and Rematch Build a Rematch plugin from scratch

Product Details

Country selected

Publication date : Aug 27, 2021
Length 286 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781801076210
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Aug 27, 2021
Length 286 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781801076210
Category :

Table of Contents

18 Chapters
Preface Chevron down icon Chevron up icon
1. Section 1: Rematch Essentials Chevron down icon Chevron up icon
2. Chapter 1: Why Redux? An Introduction to Redux Architecture Chevron down icon Chevron up icon
3. Chapter 2: Why Rematch over Redux? An Introduction to Rematch Architecture Chevron down icon Chevron up icon
4. Chapter 3: Redux First Steps – Creating a Simple To-Do App Chevron down icon Chevron up icon
5. Chapter 4: From Redux to Rematch – Migrating a To-Do App to Rematch Chevron down icon Chevron up icon
6. Section 2: Building Real-World Web Apps with Rematch Chevron down icon Chevron up icon
7. Chapter 5: React with Rematch – The Best Couple – Part I Chevron down icon Chevron up icon
8. Chapter 6: React with Rematch – The Best Couple – Part II Chevron down icon Chevron up icon
9. Chapter 7: Introducing Testing to Rematch Chevron down icon Chevron up icon
10. Chapter 8: The Rematch Plugins Ecosystem Chevron down icon Chevron up icon
11. Section 3: Diving Deeper into Rematch Chevron down icon Chevron up icon
12. Chapter 9: Composable Plugins – Create Your First Plugin Chevron down icon Chevron up icon
13. Chapter 10: Rewrite a Full Code Base from JavaScript to TypeScript Chevron down icon Chevron up icon
14. Chapter 11: Rematch with React Native and Expo – A Real-World Mobile App Chevron down icon Chevron up icon
15. Chapter 12: Rematch Performance Improvements and Best Practices Chevron down icon Chevron up icon
16. Chapter 13: Conclusion Chevron down icon Chevron up icon
17. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.