React’s state management: When to use Redux, Recoil, and Hooks.
The rapid growth of React over time. Has seen numerous state management libraries emerged as a result of ReactJS.
A significant factor in facilitating application development is knowing which state management library to select for a given project.
In this article, we will talk about the best uses of Redux, Hooks, and Recoil for managing state in a typical React application.
Note: Readers who are interested in creating a React application that calls for a state management library will find this tutorial helpful.
Introduction to state management in React is not covered in this article. It necessitates some familiarity with Redux, hooks, and React fundamentals; Therefore, before proceeding with the remainder of this article, please review the fundamentals if you are just starting out with React and state management in React.
Brief Explanation of State
The simplest way to describe State is as a JavaScript object that represents the part of a component that can change in response to a user action. You could also say that states are just a component’s memory.
In a typical React app, when a user does something, the state of the component changes. This isn’t bad, but if the app starts to grow, it quickly becomes a problem; As a result, keeping track of all dependencies is extremely challenging due to the app’s complexity.
Let's say we're making an application for online shopping; The shopping cart, buttons, view cart session, checkout, login bar, and so on can all be components in an app like this. In this app, a single user action of adding items to the cart can have a significant impact on a number of other parts by:
- adding the cart to the user’s cart history.
- changing the state of the cart component itself,
- and checking out products.
This only scratches the surface of the many other features that we could incorporate into the online shopping app. In the long run, the engineers in charge may encounter numerous bugs and issues if they do not take scalability into account when developing the app.
An app like this could end up being a pain to constantly update and debug.
The preceding examples demonstrate the significance of the state in typical React applications.
In this application, we can use any library we want to manage the state; Regardless, they would still complete the task.
Typically, the state must be transferred to the next closest parent component before reaching an ancestor shared by both components that require it and being passed down. This procedure can be overwhelming and makes it difficult to maintain the state. It might sometimes allow you to send data to parts that don't even need it.
As the app grows in size, state management becomes disorganized. As a result, you need a state management tool like Redux or Recoil to make maintaining these states easier.
In the following sections, we will practically examine each of the state management libraries (Redux, Hooks, and Recoil), their distinctive characteristics, and the factors to take into consideration before selecting one.
Redux
Redux is the first item on our list; It was the very first react-based state management library, and it has been around for some time.
To solve the issue in our online shopping app, the state management library Redux was developed. It gives you a JavaScript object called the store, which, once set up, includes all of your application’s states and updates them as needed. A simplified illustration of Redux’s operation can be found below.
When should you useRedux?
At the time of writing, Redux is one of the most widely used React state management libraries.
When to use Redux in an application is the topic of this section.
First and foremost, Redux makes it possible to control the state of your app from a single location and to keep app changes more predictable and traceable. It makes it easier to see when your app is changing. Sadly, each of these advantages comes with specific restrictions and tradeoffs.
When using Redux, developers frequently feel that it adds additional boilerplate code, making small things appear to be overwhelming; However, that is entirely dependent on the architectural choice made by the app.
When managing state locally starts to look messy, this is one of the easiest ways to tell when you really need to use Redux.
State sharing among components becomes tedious as the app grows.
At that point, you would begin looking for ways to simplify the procedure.
We'll discuss the benefits of using Redux alongside React in the following section.
Benefits of using Redux?
When you use Redux with React, you don't have to worry about lifting upstate, making it easier to track which action causes any change and simplifying the app.
Let's examine some of the drawbacks of using Redux for state management.
Support for the Community
As the official binding library for React and Redux, React-Redux has a large user base. that makes it simpler to seek assistance, acquire knowledge of best practices, employ libraries based on React-Redux, and apply your knowledge to a variety of applications.
On Github, it is the most popular React state management library.
Improves Performance
By ensuring that only the connected component re-renders when it is required, React Redux ensures performance optimization; As a result, maintaining a global state for the app would not cause any issues.
The state is always predictable
In Redux, which makes the state predictable. Reducers are pure functions, so even if the same state and action move to a reducer, they will produce the same result. Also, the state never changes and is immutable. It makes difficult operations like infinite undo and redo possible. Time travel, or the ability to travel back and forth between previous states and view the outcomes in real time, is another possibility.
State persistence on local storage
It is possible to store some of the app's state and restore it after a refresh on local storage. It makes it really cool to store things like cart data on local storage.
Rendering on the server
We can also render on the server using redux. By sending the app's state and response to the server's request, you can manage the app's initial render with it.
Redux is maintainable
Because Redux is strict about how code should be designed, it is easy for someone who is familiar with the framework to comprehend any Redux application structure. In most cases, it makes maintenance simpler. You can also use it to separate your component tree and your business logic. It is essential to keep your app more predictable and easy to maintain for large-scale applications.
Debugging made easy
Redux facilitates application debugging in a straightforward manner. It is simple to comprehend coding errors, network errors, and other types of production-related bugs by logging actions and state.
It has excellent DevTools, which, in addition to logging, enable you to time-travel actions, persist actions upon page refresh, and other features. Debugging takes more time than actually developing features for medium- and large-scale apps.
Even though Redux has advantages, you shouldn't use it in all of your apps.
Without Redux, your application can function well.
Recoil
Recoil appears to be the most recent tool in the state management community, which includes numerous excellent libraries such as Context, Mobx, and Redux, among others.
I'd like to point out that this new state management library is not the "official" state management library for React before I go into specifics about Recoil.
However, the record demonstrates that it was developed and released by Facebook's team of React developers.
Recoil, on the other hand, is not an official state management library for React, just as Redux is not. However, if it proves useful to the React ecosystem as a whole, it may gain widespread adoption among React enthusiasts.
Problem Recoil solves
Although Recoil has a learning curve, it still solves the same problem as the majority of other state management libraries: global management of states.
Following a brief period of use, I believe these distinctions make Recoil very useful.
React-like approach and simplicity
Recoil's unparalleled simplicity is why it is on this list.
Recoil feels like using a global version of React's useState, but you can build any app you want with it, just like you can with Redux or MobX. It also supports Concurrent Mode, which is a huge plus (this is still being worked on at the time this article was written).
In contrast to Redux and Mobx, Recoil does not have a steep learning curve.
Except for Atom and Selectors, which are simple to comprehend, there is not much else to learn about them.
App-wide observation
Recoil does a good job of handling app-wide state observations, just like other state management libraries. Recoil has additional advantages, including;
Distributed and incremental state definition without boilerplate API Recoil's central core concepts are Atoms and Selectors; This section cannot be covered in this article. However, their documentation provides a comprehensive overview.
When to use Recoil
Recoil has grown so much in less than two years that it now has more than 15k stars on Github. In addition, it is gradually gaining popularity and widespread adoption among React enthusiasts and the entire React community.
Therefore, when to use Recoil may solely depend on the architecture decision made for your app; however, if you value simplicity, you may immediately begin using Recoil.
Using React Hooks
React hooks One of the best additions to the React library since its inception is the hooks feature. Hooks gave functional components "state." Like class components, functional components can now independently create and manage local states.
UseState, useEffect, useReducer, and other React hooks should be familiar to anyone who is already using React.
In this section, we’ll talk about how useful it is to use React Hooks on their own without having to use any other state management library.
Without a library, you could use React Hooks as your primary state management tool; however, this will depend on your previous experience with and comprehension of React hooks.
They can do almost anything an external library could, and they are powerful on their own.
There are some benefits to using other state management tools to some extent. Still, starting is hard because of their procedures. Similar to Redux, our application requires some boilerplate code to function; As a result, it adds unnecessary complexity.
On the other hand, in order to get our app to work, we don't need to install any additional libraries because of the useContext API and React Hooks. It makes global state management in React applications much simpler and easier to manage.
Note: In the event that you are already familiar with useState, we will investigate two hooks that support the state management process in React.
The useReducer Hook
React 16.8 included the useReducer Hook. The useReducer Hook, like the JavaScript reduce() method, takes a reducer function and an initial state as arguments and returns a new state:
We have defined our state and the dispatch method that handles it in the snippet above. The useReducer() Hook will carry out an action based on the type that our method receives in its action argument when we call the dispatch method:
useContext
This hook is used to obtain a Provider’s current context. We make use of the React.createContext API to create and provide a context.
Using useReducer and useContext
Together Using useContext and useReducer raises the level of component co-located state management.
Out of nowhere we can pass the state compartment made by useReducer and its dispatch capability to any part from any high level part. It might also be the most important part of making the state "global." React’s Context API makes your state and dispatch function available anywhere, even if you don’t explicitly pass everything down the component tree using React props.
In conclusion,
we discussed the most popular state management tools for React, their significance to React state management, and their application in particular projects.
I’d like to learn more about how you handle state in a typical React application.
Feel free to leave a clap 👏 or a comment.
You can follow me on Twitter IzickEtor