DEV Community

Cover image for Basic Principles of Redux
Hardeep Singh
Hardeep Singh

Posted on • Originally published at techbrainshub.com

Basic Principles of Redux

Redux is a state managing library used in JavaScript applications. It manages the state of your application or in simple words, it is used to manage the data of the application.

It is used with a library like React etc.

In this article we will cover three basic principles of Redux.

The first principle of Redux

You represent whole state of your application as a single JavaScript object

State example for a counter application

{
    CounterValue: 0
}
Enter fullscreen mode Exit fullscreen mode

Your application may be a simple one like counter example, TodoList example or a complex application with a lot of UI, and change of state, you are going to represent the whole state of your application as a single JavaScript object.

The second principle of Redux

State tree is read only. You cannot modify or write to it.

How you change the state?

Anytime you want to change the state, you need to dispatch an action.

What is Action?

An action is a plain JavaScript object describing the change. Example increment counter value or decrement counter value.

{
       type: 'INCREMENT'
}
Enter fullscreen mode Exit fullscreen mode
{
       type: 'DECREMENT'
}
Enter fullscreen mode Exit fullscreen mode

Pure vs Impure Functions

To understand this principle we will have to differentiate between pure and impure functions.

Pure functions:

Pure functions do not have any network or database calls.

  • They just calculate the new value.
  • If you call the pure function with the same set of arguments or parameters, you’re going to get the same returned value.
  • Pure functions are predictable.
  • They do not modify the values passed to them, see following example
function cube(x) {
  return x*x*x;
}
Enter fullscreen mode Exit fullscreen mode

Impure functions:

Any function that changes the internal state of one of its arguments or the value of some external variable is an impure function . They may have any side effects like network or database calls and it may modify the arguments which are passed to them.

function getSquare(items) {
  var len = items.length;
  for (var i = 0; i < len; i++) {
    items[i] = items[i] * items[i];
  }
  return items;
}
Enter fullscreen mode Exit fullscreen mode
  • These functions may call the database or the network,
  • They may operate on the DOM,
  • They may override the values that you pass to them.

The third principle of Redux

To describe state mutations/changes, you have to write a function that takes the previous state of the app, the action being dispatched, and returns the next state of the app.

  • This function has to be pure.
  • This function is called the “Reducer.”

Alt Text

Complete Article link and more related to Redux and React

Top comments (0)