react js-tutorial

React State Management with example

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.

What is state?

The state of a React component at a certain instance represents the value of one of its dynamic attributes. For each component, React provides a dynamic data store. This provides access to the internal data, which depicts the state of a React component. state a component member variable. When a component’s state changes, it will automatically re-render itself by invoking the render() method with the updated state.

Analyzing a real-time clock component might serve as a straightforward example to help one grasp state management. The primary function of the clock component is to display the current location’s date and time. The clock component should keep the current date and time in its state because the current time will change every second. The render() method of the clock is called every second because the state of the clock component changes every second, and the render() method uses the clock’s current state to display the current time.

What is React State Management?

React components have a built-in state object. The state is encapsulated data where you store assets that are 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.

Why do you need React 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.

Let’s discuss how to use react state management using react hooks and redux

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.

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(). 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
  };
}


Reducers in Redux

Reducers specify how the application’s state changes in response to actions sent to the store. An example of how Reducer works in Redux is as follows:

 const TODOReducer= (state = {}, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return {
        ...state,
        ...action.payload
      };
    default:
      return state;
  }
};

Store in Redux

The store holds the application state. You can access stored state, update the state, and register or unregister listeners via helper methods.

Let’s create a store for our TODO app:

const store = createStore(TODOReducer);

In other words, Redux gives you code organization and debugging superpowers. This makes it easier to build more maintainable code, and much easier to track down the root cause when something goes wrong.

Example

The fundamental parts of Redux in the codebase that differentiates it from the other tools are slices. They contain all the logic of actions and reducers.

// slices/counter.js

import { createSlice } from "@reduxjs/toolkit";

export const slice = createSlice({
  name: "counter",
  initialState: {
    value: 0
  },
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    }
  }
});

export const actions = slice.actions;
export const reducer = slice.reducer;

// store.js

import { configureStore } from "@reduxjs/toolkit";
import { reducer as counterReducer } from "./slices/counter";

export default configureStore({
  reducer: {
    counter: counterReducer
  }
});


// index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './App'
import store from './store'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

// App.js

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { actions } from "./slices/counter";

const App = () => {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <div>
        <button onClick={() => dispatch(actions.increment())}>Increment</button>
        <span>{count}</span>
        <button onClick={() => dispatch(actions.decrement())}>Decrement</button>
      </div>
    </div>
  );
};

export default App;

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.