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.
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.
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.
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.
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());
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
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.
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.
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) } }) };
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 is a Full-Stack developer with 2+ years of experience. He has experience in web technologies like React.js, JavaScript, HTML, and CSS. His expertise is building Node.js-integrated web applications, creating REST APIs with well-designed, testable and efficient and optimized code. He loves to explore new technologies.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
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.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
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.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork