Everything About Redux

What is it? How does Redux work? When to use Redux? And more

Arvin mostafaei
Apr 12 · 7 min read
image by Sandro Katalina on Unsplash

Redux is an open-source JavaScript library for managing application state. It is most commonly used with libraries such as React or Angular for building user interfaces(UI). Similar to (and inspired by) Facebook’s Flux architecture, it was created by Dan Abramov and Andrew Clark.

{Wikipedia}

Redux is a predictable state container designed to help you write JavaScript apps that behave consistently across client, server, and native environments and are easy to test.

While it’s mostly used as a state management tool with ReactJs, you can use it with any other JavaScript framework or library like Angular, Vue.js and… . It’s lightweight at 2KB (including dependencies), so you don’t have to worry about it making your application’s asset size bigger.
With Redux, the state of your application is kept in a store, and each component can access any state that it needs from this store.

Why should we use Redux(what problem does Redux solve)?

What to learn can be an overwhelming question for a JavaScript developer. It helps to narrow the range of options by learning one thing at a time and focusing on problems you find in your work. Redux is a pattern for managing application state. If you do not have problems with state management, you might find the benefits of Redux harder to understand. Some UI libraries (like React) have their own state management system. If you are using one of these libraries, especially if you are just learning to use them, we encourage you to learn the capabilities of that built-in system first. It might be all you need to build your application. If your application becomes so complex that you are confused about where state is stored or how state changes, then it is a good time for Redux to come to the scene.

We recommend that most new learners should focus on learning React first, and wait to learn Redux until after you’re already comfortable with React. “Redux doc”

Redux makes the state predictable

In Redux, the state is always predictable. If the same state and action are passed to a reducer, the same result is always produced because reducers are pure functions(if you don’t know about pure function, I recommend you to read this article). The state is also immutable(never changed). This makes it possible to implement arduous tasks like infinite undo and redo.

easy Debugging with Redux

Redux makes it easy to debug an application. By logging actions and state, it is easy to understand coding errors, network errors, and other forms of bugs that might come up during production.
For medium and large-scale apps, debugging takes more time then actually developing features. Redux DevTools makes it easy to take advantage of all Redux has to offer.

Ease of testing

It is easy to test Redux apps since functions used to change the state of pure functions.

Server-side rendering

Redux can also be used for server-side rendering. With it, you can handle the initial render of the app by sending the state of an app to the server along with its response to the server request. The required components are then rendered in HTML and sent to the users.

Community and ecosystem

This is a huge plus whenever you’re learning or using any library or framework. Having a community behind Redux makes it even more appealing to use.

When and when not to use Redux?

Photo by Javier Allegue Barros on Unsplash

all apps don’t need Redux. redux is not necessarily for every project. It’s important to understand the kind of application that you’re building, the kinds of problems that you need to solve it, and what tools can best solve the problems you’re facing.

Redux helps you deal with shared state management, but like any tool, it has trade-offs. It’s not designed to be the fastest or shortest way to write code. It’s intended to help answer the question “When did a certain slice of state change, and where did the data come from?”, with predictable behavior. There is more code to write and more concepts to learn. It also adds some indirection to your code, and asks you to follow certain restrictions. It’s a trade-off between short term and long term productivity.

You’ll know when you need Flux. If you aren’t sure if you need it, you don’t need it. Pete Hunt

I would like to amend this: don’t use Redux until you have problems with vanilla React. “Dan Abramov”(one of the creator of Redux)

Photo by Jo Szczepanska on Unsplash

What is state management in Redux?

State management is essentially a way to facilitate communication and sharing of data across components. It creates a tangible data structure to represent the state of your app that you can read from and write to. That way, you can see otherwise invisible states while you’re working with them.

Most libraries, such as React, Angular, etc. are built with a way for components to internally manage their state without any need for an external library or tool. It does well for applications with few components, but as the application grows bigger, managing states shared across components becomes a chore.

In an app where data is shared between components, it might be confusing to actually know where a state should live. Ideally, the data in a component should live in just one component, so sharing data among sibling components becomes difficult.

For instance, in React, to share data among siblings, a state has to live in the parent component. A method for updating this state is provided by the parent component and passed as props to these sibling components.

How Redux works

The way Redux works is very simple. There is a central store that holds the entire state of the application. Each component can access the stored state without having to send down props from one component to another.
There are three building parts: actions, store, and reducers. Let’s briefly discuss what each of them does. This is important because they help you understand the benefits of Redux and how it’s to be used. We’ll be implementing a similar example to the login component above but this time in Redux.

Let me tell you what each does.

ACTIONS

In a nutshell, actions are events. Actions send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The store gets information only from actions. Internal actions are simple JavaScript objects that have a type property (usually constant), describing the type of action and payload of information being sent to the store.

{
type: Signin_FORM_SUBMIT,
payload: {username: ‘jacob’, password: ‘1234’}
}

Actions are created with action creators. That sounds obvious. They are functions which return actions.

function UserAuth(form) {
return {
type: Signin_FORM_SUBMIT,
payload: form
}
}

Calling actions anywhere in the app, then Use the dispatch method, like this :

dispatch(UserAuth(form));

REDUCERS

It’s based on the array reduce method, where it accepts a callback (reducer) and lets you get a single value out of sums of integers, multiple values or an accumulation of streams of values. In Redux, reducers are pure functions that take the current state of the application and an action and then return a new state. Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state:

function Auth(state, action) {
return _.assign({}, state, {
auth: action.payload
});
}

For more complex apps, using the combineReducers() utility provided by Redux is possible (indeed, recommended). It combines all of the reducers in the app into a single index reducer. Every reducer is responsible for its own part of the app’s state, and the state parameter is different for every reducer. The combineReducers() utility makes the file structure much easier to maintain.

If an object changes only some values, Redux creates a new object, the values that didn’t change will refer to the old object and only new values will be created. That’s great for performance.

const rootReducer = combineReducers({
handleAuth: handAuth,
editProfile: editProfile,
ResetPassword: ResetPassword
});

STORE

Store is the object which holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers. That makes Redux simple and predictable.

import { createStore } from ‘redux’;
let store = createStore(rootReducer);
let authInfo = {username: ‘jacob’, password: ‘1234’};
store.dispatch(UserAuth(authInfo));

Do I need a special build-tool to use Redux?

Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel. You should be able to use it regardless of your JavaScript build process. Redux also offers a UMD build that can be used directly without any build process at all.

Can Redux only be used with React?

Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Vue, and more. Redux simply provides a subscription mechanism which can be used by any other code. That said, it is most useful when combined with a declarative view implementation that can infer the UI updates from the state changes, such as React or one of the similar libraries available.

Summary

In the end, Redux is a great library, it’s quite good for managing the state of your application.
it is used by top companies like Uber, Khan Academy, Twitter, it’s gained a lot of traction and there are some great reasons to use it, but there are also reasons you might not want to use it. Make informed decisions about your tools, and understand the trade-offs involved in each decision.

Good luck:)

CodeX

Everything connected with Tech & Code

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store