If you don't use Redux, complex patterns are needed to communicate changes between the application components. Redux simplifies this by emitting state changes to components by using the Redux store (or application store). Within a React Redux application, components will subscribe to the store while the store emits changes to the components. This image describes perfectly how Redux works:
Redux handle the states as immutable. However, objects and arrays in JS are not, which can cause us to mutate the state by mistake.
There are three principles of Redux:
- Single source of truth: The state of your whole application is stored in an object tree within a single store.
- The state is ready-only: The only way to change the state is to emit an action, an object describing what happened.
- Changes are made with pure functions: To specify how the state tree is transformed by actions, you write pure reducers.
What are the actions?
Actions are payloads of data send it from your application to the store. They are the only source of information for the store. You send them to the store using the method store.dispatch(). The actions are JS objects and must have a node called type which indicates the type of the action being executed and a payload that is the data contained in the action.
What is immutability?
Immutability is a core concept in Redux. In order to change a Redux state, a new object must be returned.
The immutable types in JS are:
The mutable types in JS are:
Why Redux uses immutability?
- Is more clear: We know who changed the state (reducers)
- Has better performance
- Easy to debug: You can use Redux DevTools to debug
There are many ways to work with immutability:
- Using ES6:
- With Object.assign
- With Spread operator (...)
- Using libraries:
- Lodash (merge and extend)
What is a reducer?
The reducer is similar to a meat grinder. In the meat grinder, you add the ingredients on the top (state and action), and then on the other side, the result is the new state.
In other words, the reducer is a pure function that receives two parameters: the actual state and the action, and will return a new state that is immutable.
Types of components
There are two types of components:
- Is connected to Redux (connect)
- Focuses on how things work
- Dispatch actions
- Generated by react-redux
- Is not connected to Redux
- Focus on how things look
- Receives data or function via props
- Normally are Stateless components
The flow of Redux starts when you call an action from the UI, This action will send an object with data (type and payload) to the store. The store interacts with the reducers to update the state based on the action type. Once the state is updated on the reducer, it returns the value to the store, and then the store sends the new value to the React application.
In the next post, I'll show you how to create your first Redux Store. If you want to learn more about React and Redux you definitely need to get my React Cookbook!