How to use Redux with jQuery

State management is one of most integral parts of any software and a buggy implementation is enough to break the application and produce a lot of functional bugs. State management reduces the response time to get the data either from the database or from any data store, which results in faster page loading. Earlier, state management was only possible on the server side.

However, with the growth of new and powerful client side frameworks and technologies, it is now possible to implement client side state management as well. Redux is one of the options available for client side state management. Redux is a predictable state container for JavaScript apps. It’s a mechanism to store and share the data on the client side within the application.

Redux is generally used in combination with React, but it's not tied to React. It is written in vanilla JavaScript which makes it compatible with other libraries such as jQuery, Angular, Backbone, or Cycle.js. This post reviews Redux and its core concepts and then demonstrates how to use it with jQuery. We’ll be creating 2 applications to demonstrate the use of Redux with jQuery. The first application deals with simple string values, the second with an application using an object.

What is Redux?

From the official documentation, “Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.”

In other words, Redux is a tiny library (only 2KB, including dependencies) which helps you to maintain state on the client side. It’s more like a backend database on the client-side that stores the information needed to form the client side UI. Pretty simple, but what is state?

One can refer to state as a single object or a collection of objects, available to the whole application. This data may vary based on the application. For an e-commerce application, it can be a list of products, related products, customer information, order history and much more.

Here are some of the features/pros of Redux:

• It’s a lightweight implementation of Facebook’s flux pattern.
• It stores the application state in a single immutable object.
• The application state is immutable, which means no modification is allowed once added. It replaces the existing state with a new state. This makes data handling a lot safer.
• It supports hot reloading, which in turn makes debugging easy and fast.
• It also supports time travel debugging, which allows you to go backward to a previous point in your state.
• It is strict about how code should be organized which makes code easier to maintain.

Redux is great, but there also exists heavy competition with other options and one of them is Flux. Developers find them to be similar since both are designed for the state management, but in fact they are different. Redux is not completely different from Flux as it follows the same architecture, but Redux reduces some of the complexity that you find with Flux. Let’s take a look at the differences:

Redux vs Flux

• Flux is a pattern and Redux is a library.
• Flux has multiple stores, where Redux puts all the state of the application in one object.
• In Flux, the state is mutable, where Redux offers immutable object state.
• Flux has multiple stores that change the state of the application and changes are notified via a dispatcher. Redux doesn’t have a dispatcher. It relies on pure functions called reducers. Each action is handled by one or more reducers to update the single store. Since data is immutable, reducers return a new updated state that updates the store.

Redux Components

There are 3 major components of any Redux application. These are Actions, Reducer and Store. The below diagram shows the relationship between these components:

Untitled

Let’s take a look at each in brief.

Actions: Actions can be referred to any interaction made by the user, such as a button click. Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch(). They are plain JavaScript objects that denote what has changed and offer a type property as an identifier for the reducer. Actions must have a type property that indicates the type of action being performed. Typically, types should be defined as string constants. Example:

{
 type: 'INCREMENT',
 value: 5
 }

Actions are created and dispatched by action creators which are helper methods. Actions are then run by Reducers.

Reducers: Actions describe that something happened, but don't specify how the application's state changes in response. This is the job of reducers. Reducers are a pure function that takes the previous state of the application and an action and then returns a new state. Example:

function counter (state = 0, actions) {
 switch (actions.type) {
 case 'INCREMENT': return state + 1;
 case 'DECREMENT': return state - 1;
 default: return state
 }
 }

It’s a common practice to define the initial state as a default parameter (first line) and handle each action with a switch statement.

Store: Actions define what has changed and reducers return a new state based on the actions. The store is the object that brings them together. It holds the application state and provides helper methods to access the state, dispatch actions and register listeners. The below code creates an application level store. Here, counter is the name of the reducer.
const store = Redux.createStore(counter);

To dispatch any action,

store.dispatch({type: 'INCREMENT'}));

To get state,

store.getState()

Now, let’s see how to use Redux with jQuery.

Use Redux with jQuery

Redux is originally written in ES6 and needs to be transpiled into ES5 using JavaScript preprocessor. You can either use WebPack or Babel. For the purpose of this tutorial, we will be using Babel.
Babel is a transpiler for JavaScript best known for its ability to turn ES6 (the next version of JavaScript) into code that runs in your browser (or on your server) today. You should read this guide for babel setup with your tools.
For the demo, I will also be using JSFiddle. It’s an online playground to test your HTML, CSS and JavaScript code right inside the browser. You need to configure JSFiddle to use Babel.

To set Babel as you transpiler:

• In the JavaScript pane, click on settings icon.
• In the language dropdown, select Babel + JSX.

Please refer to this image for reference:

Untitled

To demonstrate using jQuery with Redux, the first sample application will allow users to select a Gender from a radio button list and then, using Redux, we will store the selected gender and display it on screen. First, let’s take a look at the HTML.

HTML

The HTML contains a radio button list with 3 possible options and a SPAN element to display the selected gender.
Male
Female
Other

jQuery

To use Redux with jQuery, include reference of the Redux library along with jQuery. You can include the reference of the Redux library from the CDN. The link to include it from CDN:
https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js

In the jQuery code, first you’ll need to define the reducer since in order to create a store we need to pass a reducer name. As mentioned earlier, the reducer is a pure function that accepts the previous state + an action and then returns the new state. The following code creates a reducer with label ‘reducer’.

const reducer = (state = 0, actions) => {
 switch (actions.type) {
 case 'MALE':
 state = "Male";
 break;
 case 'FEMALE':
 state = "Female";
 break;
 default:
 state = "Other";
 break;
 }
 return state;
 }

The reducer function declares a switch case statement based on the action type and accordingly updates the state with the new action value and returns the same. You must have at least one reducer in your application.
Next, we’ll create the store. Creating a store is very simple and can be done with just one line of code.

const store = Redux.createStore(reducer);

Our store and reducer are now ready. The only remaining piece is to create actions. To get selected gender, attach a change event to the radio button list using jQuery and then, using store.dispatch(), dispatch the action. The following jQuery code does the same thing:

$('input[type=radio][name=gender]').change(function() {
 store.dispatch({
 type: this.value.toUpperCase()
 })
 });

If you recall actions need to have type property to denote what has changed. In this case, the value of the type property is set to a selected gender and converted to uppercase as in the reducer function. Switch case comparison is done in upper case.
Now we simply subscribe to update the UI when the store is updated. We have defined a span element to display the selected gender, so the following code will subscribe for changes and will update the span element HTML with the selected gender.

store.subscribe(() => {
 $('#spnSelected').html("Selected Gender: " + store.getState() + "");
 });

Here is the complete jQuery code.

// Reducer
 const reducer = (state = 0, actions) => {
 switch (actions.type) {
 case 'MALE':
 state = "Male";
 break;
 case 'FEMALE':
 state = "Female";
 break;
 default:
 state = "Other";
 break;
 }
 return state;
 }
// Store to hold state of the app
 const store = Redux.createStore(reducer);
$('input[type=radio][name=gender]').change(function() {
 store.dispatch({
 type: this.value.toUpperCase()
 })
 });
// Subscribe() to update the UI when state changes.
 store.subscribe(() => {
 $('#spnSelected').html("Selected Gender: " + store.getState() + "");
 });

That’s it. Simple and straight forward. You can check out the code in action here.
Now, let’s create an application that’s a little more complex by storing an object in Redux store.

HTML

The HTML has 2 input boxes for Name and Email address, a button to update the data and a SPAN element to display data from the Redux store.

Name:

Email:


jQuery

In the jQuery code, first create the reducer function named updateNameReducer. The reducer function creates a new state based on the new values for inputs and returns the same. The new state is created using Object.assign(). The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

The method accepts 3 parameters:
1. Empty object – This ensures that a new object is created and returned. This ensures immutability.
2. Target - Target object
3. Source – New source of values

const updateNameReducer = (state = {}, actions) => {
 let {
 name = '', email = ''
 } = actions;
 switch (actions.type) {
 case 'UPDATE_INFO':
 return Object.assign({}, state, {
 name: actions.value.name,
 email: actions.value.email
 });
 default:
 return state
 }
 }

Next, create the store.

const updateNameStore = Redux.createStore(updateNameReducer);

Now, attach a click event to btnUpdate to create actions. The values are passed to action along with the type. In the click event, get the values of both the input boxes and dispatch the same.

 $('#btnUpdate').click(function() {
 let name = $('#txtName').val();
 let email = $('#txtEmail').val();
 updateNameStore.dispatch({
 type: 'UPDATE_INFO',
 value: {name, email}
 });
 });

Finally, subscribe to the store to update the UI for any state changes. Get the store value and assign it to the span element. The following code subscribes for changes and updates the span element HTML with store values:

 updateNameStore.subscribe(() => {
 let {
 name,
 email
 } = updateNameStore.getState();
 $('#spnResult').html('The name is: ' + name + ' and email address is:  ' + email + '');
 });
 Below is the complete jQuery code:
 // Reducer
 const updateNameReducer = (state = {}, actions) => {
 let {
 name = '', email = ''
 } = actions;
 switch (actions.type) {
 case 'UPDATE_INFO':
 return Object.assign({}, state, {
 name: actions.value.name,
 email: actions.value.email
 });
 default:
 return state
 }
 }
 const updateNameStore = Redux.createStore(updateNameReducer)
 $('#btnUpdate').click(function() {
 let name = $('#txtName').val();
 let email = $('#txtEmail').val();
 updateNameStore.dispatch({
 type: 'UPDATE_INFO',
 value: {name, email}
 });
 });
 updateNameStore.subscribe(() => {
 let {
 name,
 email
 } = updateNameStore.getState();
 $('#spnResult').html('The name is: ' + name + ' and email address is:  ' + email + '');
 });

That’s it. You can check out the code in action here.
Note: The sample code in this post is based on ES6. If you are not familiar then you can instantly transpile and see ES5  equivalent code online at es6console.

Conclusion

State management is a critical part of any application and Redux is an ideal choice for client side state management. It is one of the most popular libraries for state management due to its functional programming and immutable data store, which allows for safer data handling. It provides convenient debugging, easy to test code and quick adaptability once the core concepts of “actions, store and reducers” are understood. This post briefly covers Redux concepts and implementing it with jQuery to store simple and complex objects in the Redux store. Though Redux isn’t a perfect fit for every application, it is definitely worth trying out!



Responsive Menu
Add more content here...