Introduction to Redux Pattern
Tags: redux, angular, react, javascript
Published: 2021-01-19 18:38:57

# Introduction to Redux Pattern

In this overview of the Redux Pattern, we'll dig into the basics and answer these pressing questions:

- *__What__ is the Redux?*
- *__Why__ do we use the Redux?*
- *__When__ do we use  the Redux?*

Redux patterns in applications created in React or Angular are very handy tools in helping define state and managing active and passive events.

## What is the Redux Pattern?

> Redux is a pattern and library for managing and updating application state, using events called "actions". - [Redux Documentation](https://redux.js.org/tutorials/fundamentals/part-1-overview)

Not only is redux great for defining events, it also guides the flow of events through predictable event tracking.

### What Redux Pattern is not

Redux and Redux patterns are not to be confused with Flux patterns or Flux architecture. The main difference between these two patterns is the "single source of truth" concept.

Stores are our single sources of truth containing the state of our application. In Flux, the store can be split and defined in multiple locations throughout the application.

Redux as a single source of truth means that we can better maintain and improve our applications by merging state and events into a single location. This single location feeding the application is one of the key considerations developing for the architecture and scalability of an application.

## Why do we use the Redux Pattern?

> ...Redux makes it easier to understand when, where, why, and how the state in your application is being updated, and how your application logic will behave when those changes occur. - [Redux Documentation](https://redux.js.org/tutorials/fundamentals/part-1-overview)

While Redux's use is simple for managing a "global" or "single source" level of state, there are some other impacting benefits:

### Predictability of Events.

When we know what event will happen next if we click a button or link, we take away all assumptions about events triggering other events.

### Better Debugging from Event Tracing.

Personally, event tracing is one of the huge benefits I like about state management because defects in events can be pinpointed accurately. If state wasn't updated correctly, we can make better logical assumptions.

### Complex State Change

State is the one thing we can rely on and sometimes this state can receive asynchronous updates from different events. Redux makes these updates easier to manage.

## When do we use the Redux Pattern?

Ideally, Redux should be used for parts of an application that share state. 

Here are a few other considerations when deciding to use the Redux pattern.

### Frequency of State Changes

State can be small or large, simple or complex, but in every case where events are performed, state will always be updated.

### Application Scalability

First, we need to predict how an application will grow in size from the number of features. As an application scales from a simple set of functions to an enterprise-level experience, duplicated code and events decrease performance.

Additionally, a Single Page Application (SPA) benefits greatly from Redux. For example, event-based routing behaves differently from a "regular" website since we conditionally generate new pages. As the SPA increases in features or pages, so does its need for state management.

### Complexity of State Changes and Logic

Sometimes application state complexity increases as the application scales. Technical debt takes on a different form when the state isn't properly managed. *Red, Green, Refactor* is a simple, effective strategy to help minimise state technical debt - debt cause from a lack of code hygiene.

In *Red, Green, Refactor* we identify what needs to change, determine how we make the change, then execute the change. In the case for state, we can merge similar portions of state together or split apart state by feature or function, making it easier to access parts of state. Likewise, any logic that relies on combined or nested state should be updated as you make those changes.

## How to Start Using Redux Today

While this is an introduction to using Redux, it's helpful to note where we can start to add it in our projects.

### File Structure
First, we defined a store location. We can choose to have this live on the same directory level as our other components and services:

```bash
    src
    |- components
    |- services
    |- ...
    |- store
        |- actions
        |- reducers
        |- ...
```

### React

Next, we can utilise state management. For vanilla JavaScript apps, we can use Redux as is, but there is special version of it created for React applications called [React-Redux](https://react-redux.js.org/). The main difference here is the React integration:

```javascript
    import ReactDOM from "react-dom";
    import ReactDOM from "react-dom";
    ...
    import { Provider } from "react-redux"; // needed to supply store to app
    import store from "./redux/store"; // your implementation of the store

    import TodoApp from "./TodoApp";

    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <Provider store={store}> // now the app has access to our store
      <TodoApp />
      </Provider>,
      rootElement
    );
```

### Angular

Similarly for the popular Angular framework, we have [NgRx](https://ngrx.io/), a version of Redux created specifically for Angular.

```typescript
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { AppComponent } from './app.component';

    import { StoreModule } from '@ngrx/store'; // needed to supply store to app
    import { todoReducer } from './store/to-do.reducer'; // your implementation of the store

    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule, StoreModule.forRoot({ todo: todoReducer })],
      providers: [],
      bootstrap: [AppComponent],
    })
    export class AppModule {}
```

You can choose your own adventure with state management. Choose wisely!

## Closing Thoughts

Talking about the glories of Redux comes with its cons as well. Keep in mind that using Redux also means defining a state that can become overly complex and require more overhead for Red-Green Refactoring. The benefits far outweigh this cost, however.

The key things to remember about Redux is that it's meant to define a predictable set of events, manage and share application state in a *single source of truth*, and should be used when a project becomes large and complex.

---

*This Dot Labs is a modern web consultancy focused on helping companies realize their digital transformation efforts. For expert architectural guidance, training, or consulting in React, Angular, Vue, Web Components, GraphQL, Node, Bazel, or Polymer, visit [thisdotlabs.com](https://www.thisdotlabs.com).*

*This Dot Media is focused on creating an inclusive and educational web for all.  We keep you up to date with advancements in the modern web through events, podcasts, and free content. To learn, visit [thisdot.co](https://www.thisdot.co).*