2019-05-08
Redux combined with React is the most popular stack right now. Almost every React user tries to pair their code with Redux. So what is Redux actually? Redux is basically a library to help managing an application's state. Redux is not only tied to React, Redux can also be used in other JavaScript library or framework such as Angular.
So why do we need state management tool such as Redux? Let's imagine if we have two different components A and B that both communicate each other using a state. Each component has several child components and it passes some data of its' state as props, and those child components also have some more child components or grandchildren components. Now the problem is, the state in those grand children components have to be lifted up and up to the grandparent component A in order to communicate with component B. This makes the state very difficult to maintain, and yet it exposes unnecessary data between child components in the middle. The problem obviously gets worse as the application gets bigger and more complex.
So how does Redux solve the problem above?
Redux works by keeping all application's state in one place called Redux store
. And each component it the application whether it is a parent or child, can access Redux store without passing props from one another.
Redux is mainly composed of three components.
The first one we have already discussed is Redux store.
The next component is called Redux action
, so what is action? It is the only way we can access Redux store. Without action we cannot modify or change the state in Redux store.
Redux action sends data to Redux store using dispatch
function.
This action is a plain JavaScript object and typically has two arguments:
The final component is called Reducers
.
Reducers are pure functions that take previous application's state, and return a new state based on the action's type. The key in implementing Reducers is to never ever mutate the data inside it, or it may cause side-effects
.
Only actions should handle side-effects, we will discuss about side-effects in another topic.
That depends on the app, not all React app needs Redux.
If two or more components needs to share state and pass it several levels down to their child components, it might be a strong indication that this app needs a state management tools such as Redux.
One common uses of Redux is keeping user's login through different pages or components of the app. Rather than props drilling
the user's login through the entire components of the app, it would be much easier to maintain if the user's login is in one place called store and every components can access it individually without the need to depend on their child or parent component.