Biggest Challenge in React application is the management of state for frontend developers. In large applications, React alone is not sufficient to handle the complexity which is why some developers use React hooks and others use state management libraries such as Redux. In this post, We are going to take a closer look at both React hooks and Redux to manage the state.

What is State?

React components has a built-in state object. The state is encapsulated data where you store assets that is persistent between component renderings. The state is just a fancy term for a JavaScript data structure. If a user changes state by interacting with your application, the UI may look completely different afterwards, because it’s represented by this new state rather than the old state.

Make a state variable responsible for one concern to use efficiently.

Why do you need state management?

React applications are built using components and they manage their state internally and it works well for applications with few components, but when the application grows bigger, the complexity of managing states shared across components becomes difficult.

Here is a simple example of an e-commerce application, in which the status of multiple components will change when purchasing a product.

  • Add that product to the shopping list
  • Add product to customer history
  • trigger count of purchased products

If developers do not have scalability in mind then it is really hard to find out what’ is happening when something goes wrong. This is why you need state management in your application.

What is Redux

Redux was created to resolve this particular issue. it provides a central store that holds all states of your application. Each component can access the stored state without sending it from one component to another. Here is a simple view of how Redux works.

Image1

There are three building parts: actions, store, and reducers. Let’s briefly discuss what each of them does.

Actions in Redux

Actions are payloads of information that send data from your application to your store. Actions are sent using [store.dispatch()](https://redux.js.org/api/store#dispatchaction). Actions are created via an action creator. Here is an example action that represents adding a new todo item:

{ 
type: "ADD_TODO", 
payload: {text:"Hello Foo"}
 }

Here is an example of its action creator:

ocnst addTodo = (text) => {
  return {
     type: "ADD_TODO",
     text
  };
}

#react #redux #react hooks #programming

React State Management using React hooks and Redux
2.05 GEEK