Engineering@ZenOfAI
May 31 · 7 min read

Why Redux?

In React, data flows in one direction from parent to child and actions flow from child to parent. This is called “Unidirectional data flow” — With this characteristic, it’s not obvious how two non-parent-child components would communicate in React.

React doesn’t recommend direct component-to-component communication this way. Even if it did have features to support this approach, it’s considered poor practice by many because direct component-to-component communication is error prone and leads to spaghetti code — just like noodles, we don’t understand the beginning and end of something.

React does offer a suggestion, but they expect you to implement it on your own.

For communication between two components that don’t have a parent-child relationship, you can set up your own global event system. … Flux pattern is one of the possible ways to arrange this.

- React docs

This is where Redux comes in handy. Redux offers a solution for storing all your application state in one place, called a store. Components then dispatch state changes to the store, not directly to other components. The components that need to be aware of state changes can subscribe to the store.

The store can be thought of like a middleman for all state changes in the application.

With Redux involved, components don’t communicate directly between each other, but rather all state changes must go through the single source of truth, the store.

With Redux, it’s clear that all components get their state from the store. It’s also clear where components should send their state changes — also to the store. The component initiating the change is only concerned with dispatching the change to the store and doesn’t have to worry about a list of other components that need the state change. This is how Redux makes data flow easier to reason about.

Redux is external to react, we need to connect react to redux which we will learn later.


When Should You Use Redux?

Redux is a valuable tool for organizing your state, but you should also consider whether it’s appropriate for your situation. Take some time to understand the potential benefits and tradeoffs of using it.

Here are some suggestions on when it makes sense to use Redux:

  • You have reasonable amounts of data changing over time
  • You need a single source of truth for your state
  • You find that keeping all your state in a top-level component is no longer efficient.

Yes, these guidelines are subjective and vague, but this is for good reason. The point at which you should integrate Redux into your application is different for every user and different for every application.

Store orchestrates all the moving parts in Redux.


Redux Installation

Move into your React development environment and install Redux.
Redux installation is pretty simple. Redux is available as a package on NPM for use with a module bundler or in a Node application:

npm install --save redux

For more details, see the Installation page.


Redux principles

Redux can be described in three fundamental principles:

  1. Single source of truth
  2. State is read-only
  3. Changes are made with pure functions

Single source of truth
The state of your whole application is stored in an object tree within a single store. This way chain reaction of direct communication among components is ruled out.

State is read-only
The only way to change the state is to emit an action, an object describing what happened.

Changes are made with pure functions
To specify how the state tree is transformed by actions, we write pure functions called reducers.


Redux in a nutshell

In the above diagram, Actions are simple Javascript objects that represent data and intent on how the state should change, we use functions called Dispatchers to send actions to Reducers. Which return new state that is updated in the Store. Store updates the State and State will define the UI.


Redux in Detail

Event changes in view trigger an action object. An action object holds the data and the intention of change to state which is then passed to dispatcher. A dispatcher is a pure function that passes this action object to Reducer (change the state), we have to dispatch an action.

Action(s) :

  • An action in Redux is a JavaScript object.
  • This Action object has two properties, one describing the type of action, and one describing what should be changed in the app state (payload).

This is what action looks like:

{
type: 'ADD_ARTICLE',
payload: { title: 'React Redux Tutorial', id: 1}
}

If you want to update the state of your application, you convey your action to the reducer. This means dispatching an action.

Action Creator(s)

Instead of dispatching an object literal directly and repeating the same action object throughout the application, you could call a function that creates and returns the action object:

const ADD_ARTICLE = 'ADD_ARTICLE';

// Action Creator
var addArticle = function(name,id) {
return { type: ADD_ARTICLE, payload:{title: name,id: id}}
}

// Dispatch still sends a plain object
store.dispatch(addArticle('React Redux Tutorial',1));

Reducer function(s) :

  • Reducer is a Pure function.
  • A reducer takes two parameters: the current state and an action to be dispatched & returns the next state of the application.

Conditions to be a Pure function:

  • It does not make outside network or database calls.
  • Its return value depends solely on the values of its parameters.
  • Its arguments should be considered “immutable”, meaning they should not be changed.
  • Calling a pure function with the same set of arguments will always return the same value.

These are called “pure” because they do nothing but return a value based on their parameters. They have no side effects into any other part of the system.

We typically, implement the reducer as a switch statement. organized according to the action types. Any other variables that need to be declared/changed will be passed in along in the action object.

create a reducer.js file :

  • A reducer must return current state for undefined actions. (we use default switch statement)
  • The state is immutable, we use pure functions (Reducers) to create a new state which is then updated to the store.

The REDUCER always “talks” to the STORE.

Reducers shouldn’t break state immutability

One could avoid mutations in redux:

Pro-tip: As your app grows so will the reducer. You can split a big reducer into separate reducer functions and combine them with combineReducers.

Remember, all reducers will receive an action when it is dispatched so there’s no way to conduct a dispatch that goes to one particular reducer.

Store

  • A store holds the whole state tree of your application.
  • There are no multiple stores and no multiple states.
  • The store is only one instance in your application.

Here’s what the code to create a Redux store looks like:

File: store.js

  • createStore( ) takes a reducer as the first argument and in our case, we passed in rootReducer.
  • You may also pass an initial state to createStore which is useful for server-side rendering but for now, we’re not interested in that.
  • The most important concept here is that the state in redux comes from reducers. Let’s make it clear: reducers produce the state of your application.
  • The Store and the Reducer are great buddies. Always in sync.
  • The Reducer is the only mandatory argument passed into createStore( ).

Actions, State & Store should only contain data which is Serializable, in other words, it converts to JSON well.

Redux store methods:
The Redux store exposes a simple API for managing the state. The most important methods are:

  1. getState for accessing the current state of the application.
  2. dispatch for dispatching an action.
  3. subscribe for listening on state changes.

Connecting React with Redux :
For connecting react with redux we use react-redux, react-redux is a redux binding for React. It’s a small library for connecting Redux and React in an efficient way.

React-redux installation:

npm i react-redux --save-dev

The most important method you’ll work with is connect. This connect method connects a React component with the Redux store.

You will use connect with the following functions depending on the use case.

  • the mapStateToProps function.
  • the mapDispatchToProps function.

mapStateToProps?

  • mapStateToProps does exactly what its name suggests: it connects a part of the Redux state to the props of a React component.
  • By doing so a connected React component will have access to the exact part of the store it needs.

mapDispatchToProps?

  • mapDispatchToProps does something similar, but for actions.
  • mapDispatchToProps connects Redux actions with React props.
  • This way a connected React component will be able to dispatch actions.

That’s all with the basic understanding of Redux concepts, let us build a small react application that stores employee details and displays them using redux in my next article.

This story is authored by Koushik Busim. Koushik is a software engineer and a keen data science and machine learning enthusiast.

ZenOf.AI

AI | Machine Learning | Big Data

Engineering@ZenOfAI

Written by

ZenOf.AI

ZenOf.AI

AI | Machine Learning | Big Data

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade