Edux is one of the hottest frameworks in front-end development recently. However, many people are not clear about what it is and what benefits it has.

As described in the development documentation, Redux is a container of predictable state for JavaScript applications. In other words, it is an application data flow framework rather than traditional libraries or frameworks like underscore. Js or AngularJs.


Redux was founded by Dan Abramov around 2015. Was inspired by Facebook’s Flux framework and the functional programming language Elm. Redux soon became popular for its simplicity, small size (only 2KB), and rich development materials. If you want to know the inner workings of Redux and want to dig deeper into the framework library, check out Dan’s free course.


Redux is primarily used for application state management. In short, Redux stores the state of the entire application in a single constant state tree (object) that cannot be changed directly. When some data changes, a new object is created (using Actions and reducers). We describe these core concepts in detail below.


 1  How is it different from MVC and Flux


To get a complete picture, let’s take a look at the traditional model-View-Controller (MVC) pattern, which most developers are familiar with. In the MVC architecture, there is a clear separation between the data (model), presentation layer (view), and logic (controller).

There’s a problem with this, especially in large applications: data flows in both directions. That is, there are many places in the code where a change in data (an input from the user or an interface return) can affect the state of the application — for example, two-way data binding. This can be difficult to maintain and debug.

Flux is similar to Redux. The main difference is that Flux has multiple stores that can change application state, and it broadcasts these changes through events. Components can subscribe to these events to synchronize with the current state. Redux does not have a dispatcher, but in Flux the Dispatcher is used to broadcast data to registered callback events. Another difference is that there are many extensions available in Flux, which also introduces some confusion and contradictions.


Benefits of using Redux

You may ask, “Why do I need to use Redux?” That’s a good question. Here are some of the benefits of using Redux in your next application:

  • There is always an accurate source of predictable results, the Store, and there is no confusion about how actions and the rest of the application are synchronized with the current state.

  • Maintainability The predictable nature of the results and strict organizational structure make code easier to maintain.

  • Organizational Redux is more critical of how your code should be organized, which makes it more consistent and easier for teams to collaborate.

  • This is very useful, especially for first renders, for better user experience and search engine optimization. Simply pass the store created by the server to the client.

  • Developer tools Developers can track everything happening in their applications in real time, from actions to state changes.

  • Community and Ecology This is a huge plus whenever you learn to use any library or framework. Having a community that supports Redux makes it more appealing to use.

  • Testability The first rule of writing testable code is to write small functions that do only one thing and stand alone. Almost all of Redux’s code is just that function: small, pure, detached.


 2  Functional programming


As mentioned, Redux is built on the concept of functional programming. Understanding these concepts is crucial to understanding exactly how and why Redux works that way. Let’s review the basic concepts of functional programming:

  • It can treat functions as first class objects.

  • It can take functions as arguments.

  • It can use functions, recursion, and arrays to control flow.

  • It can use pure, recursive, higher-order, closures and anonymous functions.

  • It can use helper functions such as Map, Filter, and Reduce.

  • It can chain functions together.

  • The state does not change (that is, it is immutable).

  • The order in which the code is executed does not matter.


Functional programming allows us to write cleaner and more modular code. By writing cleaner functions with separate scope and logic, you can make your code easier to test, maintain, and debug. Now these short functions are reusable code, so you can write less code, and less code is a good thing. Functions can be copied and pasted anywhere without modification. Functions are scoped separately so that only one task can be performed, reducing the dependency on other modules within an APP, which reduces coupling, another benefit of functional programming.

See pictures of examples of functional programming metaphors

You’ll see, among other things, that pure functions, anonymous functions, closures, higher-order functions, and chained calls are often used in functional JavaScript. Redux mostly uses pure functions, so it’s important to understand what they are.

Pure functions return a new value based on the passed parameter. They do not modify existing objects; instead, they return a new value. Such functions do not depend on something called state, and they return only one and the same result, regardless of the argument provided. As such, they are predictable.


Because pure functions do not modify any values, they do not have any effect on the scope and do not have any noticeable side effects, which means developers can only care about the values returned by pure functions.


 3  Where Redux can be used


Most developers will combine Redux with React, but Redux can be used with any other framework. For example, you can pair Redux with AngularJS, vue. js, Polymer, Ember, backbone. js and Meteor.

Redux plus React is still the most common combination, though. Make sure to learn React in the right order: The best source for getting started is Pete Hunt’s, which is useful for developers who are just getting started with React and who are overwhelmed by the front-end ecosystem.

JavaScript fatigue is a legitimate concern for front-end developers, both new and experienced, so spend time learning React or Redux in the right order and in the right way.

One of the things that makes Redux great is its ecosystem. You can find articles, study guides, middleware, tools, and sample code.

For my part, I use David Zukowski’s example code because it covers everything you need to build javascript projects with React, Redux, and React-Router.

A word of advice: Try not to use sample code libraries and beginner’s tips when learning new frameworks like React and Redux. It can be even more confusing because you have no idea how they work together.First understand it, second build a very simple app and learn it theoretically as a support project, then use the sample code as a production project to save time.


 4  Set up the Redux section


The Redux concept may sound complicated or magical, but it is straightforward. Remember that this library is only 2KB in size. Redux has three basic parts: Actions (Actions), Stores (Stores), and reducers (reducers).

View pictures of the Redux data stream


Let’s talk about what each part does.


Actions

Simply put, actions are events. Actions pass data from the application (user interface, internal events such as API calls and form submissions) to the Store. Store only retrieves information from actions. Internal Actions are simple JavaScript objects with a type attribute (usually a constant) that describes the type of action and the payload information passed to the store.

{

  type: LOGIN_FORM_SUBMIT,

Payload: {username: ‘alex’, password: ‘123456’}

}

Actions are created from the action generator. I know it sounds obvious. They’re just functions that return actions.

function authUser(form) {

  return {

    type: LOGIN_FORM_SUBMIT,

    payload: form

  }

}

It’s very easy to call actions anywhere in your application. Use the dispatch method like this:

`dispatch(authUser(form)); `

Reducers

We’ve discussed what reducer is in functional JavaScript. It is based on the array Reduce method and receives a reducer that lets you get a single value, an integer, or a collection of values from a set of values. In Redux, a reducer is a function that takes the current state and events of the application and returns a new state (pure). Understanding how joints work is crucial because they do most of the work. Here is a very simple Reducer that takes the current state and an action as parameters and returns the next state:

function handleAuth(state, action) {

  return _.assign({}, state, {

    auth: action.payload

  });

}

For more complex projects, it is possible (necessary, recommended) to use the combineReducers() instance provided by Redux. It combines all the reducers in this application into a single index Reducer. Each Reducer is responsible for the state of its own part of the application, and this state parameter is different from that of the other reducer. The combineReducers() instance makes the file structure easier to maintain.


If an object (state) changes only a few values, Redux creates a new object, those values that do not change will point to the old object and new values will be created. This is great for performance. To make it more efficient you can add Immutable.

const rootReducer = combineReducers({

  handleAuth: handleAuth,

  editProfile: editProfile,

  changePassword: changePassword

});

Store

The Store object holds the state of the application and provides assistance for accessing state, distributing state, and registering listeners. All states are represented by a store. Any action returns a new state object via the Reducer. This makes Redux very simple and predictable.

Import {createStore} from ‘redux’;

  let store = createStore(rootReducer);

Let authInfo = {username: ‘alex’, password: ‘123456’};

  store.dispatch(authUser(authInfo));

 5  Developer tools, code time travel, and hot restarts

To make Redux easier to work with, especially with large applications, I recommend using Redux DevTools. It’s very useful to show state changes over time, real-time changes, actions, and the current state. Save time and effort by avoiding console.log’s current state and actions.


View the picture Redux DevTools


One slight difference between Redux and Flux is the implementation of time travel. In Redux, you can go back to the previous state and even move your state from that point to a different position. In the Redux workflow, Redux DevTools supports these “time travel” features (think of them as git commands for state state) :

  • Reset: Resets the state of the store creation

  • Restore: Reverts to the last committed state

  • Clear: Clear all defective actions that you may have changed by mistake

  • Commit: Makes the current state initial


This feature of time travel is not productive and is intended only for development environments and debugging. The same goes for DevTools.


Redux makes testing easier because it uses functional JavaScript as its base, and small stand-alone functions are easy to test. So, if you need to change something in your state tree, just import a Reducer connector that is responsible for that state and test it separately.


 6  Build an app


Let’s finish this tutorial by building a very simple application that uses Redux and React. To make it easy for everyone to follow, I keep native JavaScript and use ECMAScript2015 and 2016 as little as possible. In this article we start with the easier login logic.

This example will not use any real data, because the purpose of this application is to show how Redux manages state in a very simple application. We use CodePen for editing.


1. The React components

We need some React components and data. We write a simple component and render it to the page. This component has an input field and a button (one divided into a simple login form). Next, we add the status text:

View the story, written by Alex Bachuk on CodePen (http://codepen.io/abachuk/pen/Meaxgm/).


2. Events and actions

Add the Redux module to the project and add the onClick event handling for the button. Once the user is logged in, we distribute the action of type LOGIN along with the value of the current user. Before we can do that, we must create a store and pass in a reducer function as one of its arguments. So far, this reducer is just an empty function:

See the code Redux introduces – step 2. Events and actions, written by Alex Bachuk on CodePen (http://codepen.io/abachuk/pen/yJYwYX/).


3. Reducers

Now we have an active action that the Reducer will take and return a new state. Let’s handle the LOGIN action to return a status that is logged in and add a LOGOUT action so we can use it later. Auth Reducer receives two parameters:

  1. The current state (with a default value),

  2. action.

See the code Redux introduces – step 3. Reducers, written by Alex Bachuk on CodePen (http://codepen.io/abachuk/pen/LZpaGX/).

4. Display the current status

Now that we have the initial state (the default in the Reducer) and the React component, let’s see what the state looks like. The best practice is to add state to the child components. Since we only have one component, we pass the state of the application as a property to the Auth component. In order for everything to work together, we have to register store listeners with a SUBSCRIBE help method, by wrapping reactdom.render in a function and passing itStore. The subscribe () :

Check the Pen Redux introduces – step 4. Display the current state By Alex Bachuk on CodePen implementation (http://codepen.io/abachuk/pen/NrGJRR/).


5. Login and logout

Now that we have the login and exit actions handled, let’s add the exit button and distribute the LOGOUT action. The final step is to manage which button is used to show login and which is used to show exit by moving the login outside the Render method and rendering the variable as follows:


View the Pen Redux introduces – step 5. Login/logout by Alex Bachuk on CodePen implementation (http://codepen.io/abachuk/pen/dXYrpr/).


 7  conclusion


Redux is gaining traction every day. It has been used by many companies (Uber, Khan Academy, Twitter) and projects (Apollo, WordPress ‘Calypso) with great success in actual production projects.

Some developers may complain that it has a lot of extra overhead. In most cases, it takes more code to represent simple actions like button clicks or simple UI changes. Perhaps simple actions and UI changes don’t have to be part of the Redux Store to be maintained at the component level.

While Redux may not be the perfect solution for your application or framework, I highly recommend checking it out, especially with React apps.


Show me, show me, show me, show me


read(Click title):

React, Redux, and wild dog chat room simple implementation

Wen: Alex Bachuk original: http://www.zcfy.cc/article/an-introduction-to-redux-ndash-smashing-magazine-770.html

Review images