React State Management: What Is It & It’s Types

The most complicated aspect of Frontend development is state management. State management determines how the data is managed within an application. With new technologies emerging every day, there is no shortage of state management libraries, So it becomes very confusing to decide which one to use for our application.

In this article, I will introduce you to some of the most popular state management libraries we can use to manage the state in our applications and also tell the advantages of rematch over the other libraries.

This article is for Frontend developers looking to explore state management libraries. We’ll explore the principles and features of different libraries. In this article, we will be discussing some of those libraries and comparing them to see which one is the best choice for your next react app. Let’s get started.

What Is React State Management?

State management is a way to communicate and share data across the components of an application. It provides a data structure representing the application state that you can read and write.

In react applications state is a JavaScript object that is a part of a component and can be changed based on the events or user actions. You can also call the state a memory of a component.

What Are the Different Types of React State Management?

1. RECOIL

Recoil was introduced in early 2020 by the Facebook team, and since its introduction, it has gained a lot of popularity among the react community. The core concepts to understand in Recoil are atoms and selectors.

Atom: It is a state unit that wraps and represents a single state property. It is the same as the react local state, but with the ability to be shared among components and created outside of them.

 const myState = atom({

   key: "myState", // unique, required key

   default: true, // default value

  });

Selectors: are the pure functions that depend upon the atom or other selectors to calculate their value, recomputing when any dependencies change. They are readable, writable and asynchronous.

const statusState = selector({

key: “statusState”,

           get: ({ get }) => {

const myState = get(myState)    // access the value of the atom

            }

           return myState ? “available” : “unavailable”

})

To use atoms and selectors you will need one of recoil hooks, like useRecoilValue or useRecoilState.

// Inside React component

Const [myState, setMyState] = useRecoilState(myState);

Const status = useRecoilValue(statusState);

This atoms and selectors approach makes recoil easy for beginners and powerful enough for advanced users.

2.  JATOI

In the world of state management, Jatoi is another library worth considering. It is similar to Recoil but with more minimalistic API support, typescript support, and broader documentation.

Apart from the above, the performance is the most significant difference between Recoil and Jatoi. Recoil tracks its state with string keys, which is why they are required and unique; this can lead to memory leaks in your application. Whereas Jatoi does not require keys and depends upon the javascript inbuilt weakMap to track its atoms, automatically optimizes the memory usage and improves performance.

Previous Recoil snippets translated to Jatoi.

Const isAvailableState = atom(true);

Const statusState = ({ get }) => {

Const isAvailable = get(isAvailableState) 

Return isAvailable ? “iAvailable” : “Unavailable”

}

Const [isAvailable, setIsAvailable] = useAtom(isAvailableState);

Const [status] = useAtom(statusState);

Jatoi includes almost all the features of recoil.

3. REDUX

Redux is a library without which every statement library list seems incomplete. Although Redux has received a lot of criticism, it is still a great and proven library for building modern solutions. The main components in Redux architecture are actions and reducers.

Action: Describes what should happen.

Reducer: A function has given a previous state and the action object and returns a new state.

The Redux model has been around for a long time, its biggest issue is it’s boilerplate. Writing multiple actions and reducers can lead to a lot of code for each action writing, which is hard to maintain. That’s where the Redux toolkit comes into the picture.

const exampleSlice = createSlice({

  name: "example",

  initialState: {

    isAvailable: true,

  },

  reducers: {

    makeAvailable: (state) => {

      state.isAvailable = true;

    },

    makeUnavailable(state) {

      state.isAvailable = false;

    },

  },

});

const { makeAvailable, makeUnavailable } = exampleSlice.actions;

const exampleReducer = exampleSlice.reducer;

const store = configureStore({

  reducer: { example: exampleReducer },

});

// Inside React components with React-Redux hooks

const isAvailable = useSelector((state) => state.example.isAvailable);

const dispatch = useDispatch();

dispatch(makeAvailable());

dispatch(makeUnavailable());

4. REMATCH

After using Redux for so long, an alternative for redux is worth mentioning. Rematch, is a lighter, faster and easier version of Redux. A rematch is built upon the Redux Core, which minimizes the boilerplate code we require for the Redux and introduces simple side-effects handling with async and await. All this fits into a small bundle size.

At the heart of Rematch are models, reducers and effects all this wraps into a single entity. This enforces the Redux best practices and makes state management easier.

const countModel = {

  state: 0,

  reducers: {

    increment(state, payload) {

      return state + payload;

    },

  },

  effects: (dispatch) => ({

    async incrementAsync(payload) {

      await new Promise((resolve) => setTimeout(resolve, 1000));

      dispatch.count.increment(payload);

    },

  }),

};

The models can then be used to create Redux stores with additional Rematch functionality.

const store = init({

  models: {

    count: countModel,

  },

});

const { dispatch } = store;

dispatch({ type: "count/increment", payload: 1 });

dispatch.count.increment(1); // Action shortcut

dispatch({ type: "count/incrementAsync", payload: 1 });

dispatch.count.incrementAsync(1); // Async action shortcut

5. REACT CONTEXT

There are situations where your applications are not that big, and adding an extra dependency can create more harm than good to our application; for such cases, React has built-in tools that we can use, are State and Context APIs. Those can do just fine for the vast majority of apps. The best choice is to always stick with the basic and lightweight until you need something more powerful.

Hire The Best ReactJS Developers

What Is Rematch?

A rematch is a more enhanced version of Redux with more features, clean architecture and less boiler code boilerplate. Rematch works on the same architecture as Redux and also includes a persistor to persist the state.

At the heart of Rematch are models, reducers and effects all this wraps into a single entity. This enforces the Redux best practices and makes state management easier.

Rematch Implementation

In this example, we will see how we can use Rematch in react application. First, we will create a store and make the store available across the application using a provider.

import React from "react";

import ReactDOM from "react-dom";

import { init } from "@rematch/core";

import { Provider } from "react-redux";

import * as models from './models';

import Count from './Count';

// generate Redux store

const store = init({

  models,

});

const Root = () => (

  <Provider store={store}>

    <Count />

  </Provider>

);

ReactDOM.render(<Root />, document.querySelector('#root'));

import React from "react";

import { connect } from "react-redux";

const Count = props => (

  <div>

    <h1>The count is: {props.count}</h1>

    <button onClick={props.addByOne}>Add 1</button>

    <button onClick={props.addOnsync}>Add 1 Async</button>

  </div>

);

const mapState = state => ({

  count: state.count,

});

const mapDispatch = ({ count: { addBy, addAsync }}) => ({

  addByOne: () => addBy(1),

  addOnesync: () => addAsync(1)

});

export default connect(mapState, mapDispatch)(Count);

In the below code, we are creating a Rematch model count, which will contain the state, reducer and effects.

// function to create a one second delay

const delay = (time) => new Promise(resolve => setTimeout(() => resolve(), time));

// count model

export const count = {

  state: 0,

  reducers: {

    addBy(state, payload) {

      return state + payload

    }

  },

  effects: (dispatch) => ({

    async addAsync(payload, state) {

      await delay(1000)

      dispatch.count.addBy(1)

    }

  })

};

Advantages Of React State Management

  1. More features
  2. Provides a clean architecture for developers
  3. Reduces boilerplate
  4. Includes a persistor to persist the data
  5. No configurations needed
  6. Built-in side effects support
  7. Support dynamically adding reducers
  8. Allows creating multiple stores
coma

Conclusion

In this tutorial, we learned the basics about the available state management libraries and how we can use them in our application. We also saw how we could determine which library suits our application requirements. After that, we have seen different ways to integrate them into our application.

Hirdesh Kumar

Hirdesh Kumar  is a Full-stack developer with 2+ years of experience. He has experience in web technologies like ReactJS, Javascript, Html, Css. His expertise is building Nodejs integrated web applications, creating REST APIs with well-designed, testable and efficient and optimized code. He loves to explore new technologies.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks
coma

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

author
George Hodulik
CEO, Stealth Startup, Ex-Google