Benefits of using Redux
In the modern programming world, companies and individual developers that work with React use also Redux. So you will probably encounter both these apps mentioned together a ton when you watch tutorials or work with React. That is because they go really well together!
Why do we want to use Redux?
Redux is a library that we would want to use if our apps get bigger and bigger and bigger and they have larger and larger state. It is really good at managing state especially large one and using React this.state doesn't make sense and gets more complicated.
Redux is useful for sharing data between containers. You have to move the state up one layer with React so that you have a parent that can share a state between the two. But with Redux this becomes easier.
Redux has predictable state management using 3 principles:
- Single source of truth
- State is read only
- Changes using pure functions
With Redux we have one single big object that describes the entire state of the app. So we have our single source of truth because React reacts based on whatever the state is. We can just have one big object that describes how the app should look and React will take care of it.
The state is read only and this encourages something called immutability which is not modifying the object and prevents unexpected errors. So the state object that we still create with Redux will actually never get modified, but instead we would create a new state after each action is taken by the user.
In Redux changes are made only using pure functions. The idea that a pure function is something that receives an input and always returns an output that is predictable. If we enter the same input 1000 times we expect that function to have the same output 1000 times.
Action, Reducer, Store
An action is something that a user does such as clicking on a button or a dropdown menu. As soon as a user clicks on something and creates an action, it goes through a reducer which is a pure function that receives an input. This input creates an output simultaneously called store. As it goes through the function, the store gets updated. Modern apps that are very interactive with lots of scrolling, highlighting, clicking, can benefit from Redux as all the actions go through one reducer. It always returns the same state based on the action and updates the store and this store will represent exactly what our app should look like.
this.state
You could technically have Redux with the state but also still keep a little bit of React state in a component. Redux doesn’t replace completely the this.state or this.setState in React. You can still use them together.