General Concepts
Explore the fundamental concepts of Redux by understanding functional programming principles, pure and impure functions, and the importance of immutability in JavaScript. This lesson helps you grasp how these concepts ensure predictable state management and guide effective use of Redux in applications.
We'll cover the following...
Redux is all about functional programming and pure functions. Understanding these concepts is crucial to understanding the underlying principles of Redux.
Functional programming centers around avoiding changing state and mutable data—in other words, making your code predictable and free of side effects.
JavaScript allows you to write code in a functional style, as it treats functions as
Pure and impure functions
A pure function returns values by using only its arguments: it uses no additional data, changes no data structures, touches no storage, and emits no external events (like network calls). This means that you can be completely sure that you will always get the same result every time you call the function with the same arguments. Here is an example of pure functions:
If a function uses any variables not passed in as arguments or creates side effects, the function is impure. When a function depends on variables or functions outside of its lexical scope, you can never be sure that the function will behave the same every time it’s called. For example, the following is an impure function:
Mutating Objects
Another important concept that often causes headaches for developers starting to work with Redux is immutability. JavaScript has limited tooling for managing immutable objects, and we are often required to use external libraries.
Immutability means that something can’t be changed, guaranteeing developers that it will have the same properties and values forever if you create an object. For example, let’s declare a simple object as a constant:
Even though the colors object is a constant, we can still change its content, as const will only check if the reference to the object has changed. To make the colors object appear immutable, we can use the Object.freeze() method:
The value of the red property will now be '#FFFFFF' since we have already updated the value.
Here, once we used Object.freeze(), the colors object became immutable. In practice, things are often more complicated, though. JavaScript does not provide good native ways to make data structures fully immutable. For example, Object.freeze() won’t freeze nested objects:
To work around the nature of our beloved language, we have to use third-party libraries like deep-freeze, seamless-immutable, or Immutable.js.