DEV Community

Victor Olaoye
Victor Olaoye

Posted on • Originally published at Medium on

Difference Between Local And Global State Management In React


Photo by Kit Suman on Unsplash

State management is a programming technique that is very essential in any web application. It involves managing dynamic piece of information that makes the user interface of any app interactive thus, making the user experience swift.

When interacting with web applications, there are different noticeable changes in the UI, ranging from toggling the navbar to adding products to carts. These are all possible with state management techniques. State management can be very complex depending on the scale of the application. In recent years, there have been a lot of ways for managing state. In this article, we’ll look at the difference between local and global state management in react.

Local State Management

In local state management, the application state(dynamic information that will keep the user’s experience as smooth as possible) is component scoped. Keep in mind that while managing states in React, states can only be passed as a prop to the child component (unidirectional data flow), but we can’t do the same for the parent component. This unidirectional data flow in react makes local state management easy.

A real-life example of local state management is an application that increases count when a button is clicked. The state of the application is within that component. useState and useReducer hooks can easily be used to manage the state.

But then, what if the states of a large-scale application needs to be managed across all components, for example an e-commerce site where users can add products to cart in a component and display the number of products added in the header component, using useState & useReducer hooks will only make things complex; this is will be explained in the next section.

Global State Management

Managing a large scale application in the scenario given above, will mean that state will be shared across all components. Since there’s no connection between the cart component and the header component, how do we get the number of products added to cart displayed on the header component?.

In this case, it is recommended to avoid passing of data through several nested children components (prop drilling), many libraries have been created to sort this issue: Redux, MobX and so on. React itself also created a hook called Context APIs which can be used to manage global states in web application.

In this article, we have now seen how to manage states both locally and globally with React hooks and other libraries to make our applications very interactive.

Notable References

Top comments (0)