React State-Management Issues

Why do we need a separate State-Management Library

What are the main problems when it comes to managing the state with raw JavaScript?

  1. Maintaining the code becomes harder.
  2. We need to update the UI manually using a state change listener.
  3. We may use same code again and again

Read More: State and State Management

Note: We can use React to solve the above limitations of JavaScript.


Dataflow of React:

React follows one-way dataflow system, which makes the application's code easier to understand. The One-way Dataflow is shown below:

oneWayDataFlow.png

  • State is the source of truth that drives our application.
  • View is the declarative description of the UI based on the current state.
  • Actions are the event that occur in the application based on user input and trigger updates in the state.

Problem of React's One-Way Dataflow:

image.png

Let's say we want to develop a Stat component that would compute the sum counts of the Counter component. To do that, the Stat component must have access to the Counter component's state. However, the issue is that Counter component can only talk to its parent or child (Not Cousins). As a result, the Counter component's count value is inaccessible to the Stat component.

To solve this issue, we need to use React's Lifting state up. So, we need to lift up the state of Counter component. After lifting the state, we can then send the state using props to the component.

image.png

Lifting state up has the drawback of requiring us to rewrite the entire structure of our application, which is a bother. If the tree is further nested, the issue will get worse. Many components in such scenario might not utilize the state but instead collect the state in order to pass it on to the following component. There will be many carriers in larger applications, which is not optimal.

image.png

To solve this issue, we just need to store our states in a separate store. The component which needs a specific state can get that state easily from that store.

image.png

Conclusion:

Even though React has its own state management system, it has some big limitations. That is why we need a separate state management library like Redux, which is currently the most popular in the JavaScript ecosystem, to implement the improved state management system.