Reader small image

You're reading from  React and React Native - Fifth Edition

Product typeBook
Published inApr 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781805127307
Edition5th Edition
Languages
Tools
Right arrow
Authors (2):
Mikhail Sakhniuk
Mikhail Sakhniuk
author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

View More author details
Right arrow

State Management in React

In the previous chapters, we explored the concept of state in React and mastered the basics of working with it using the useState hook. Now it’s time to delve deeper into the global state management of applications. In this chapter, we will focus on the global state: we’ll define what it is, its key advantages, and the strategies for its effective management.

This chapter will cover the following topics:

  • What is global state?
  • React Context API and useReducer
  • Redux
  • Mobx

What is global state?

In developing React applications, one of the key aspects that requires special attention is state management. We are already familiar with the useState hook, which allows us to create and manage state within a component. This type of state is often referred to as local, and it is very effective within a single component and very simple and easy to use.

For a clearer illustration, consider an example with a small form component, where we have two input elements and have created two states for each input:

Figure 12.1: Form component with local state

In this example, everything is simple: the user enters something into the input, which triggers an onChange event, where we usually change our state, causing a full re-render of the form, and then we see the result of the input on the screen.

However, as the complexity and size of your application increase, there will inevitably be a need for a more scalable and flexible approach to state management...

React Context API and useReducer

To organize the global state on your own, you can use tools that already exist in the React ecosystem, namely the Context API and useReducer. They represent a powerful duo for managing state, especially in situations where using third-party state managers seems excessive. These tools are ideal for creating and managing global states in more compact applications.

The React Context API is designed to pass data through the component tree without the need to pass props at every level. This simplifies access to data in deeply nested components and reduces prop drilling (passing props through many levels), as illustrated in Figure 12.4. The React Context API is particularly useful for data such as theme settings, language preferences, or user information.

Here’s an example of how to store theme settings using context:

const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
  const theme = 'dark';
 ...

Redux

The first of such tools is, of course, Redux. It is one of the most popular tools for managing state in complex JavaScript applications, especially when used with React. Redux provides predictable state management by maintaining the application’s state in a single global object, simplifying the tracking of changes and data management.

Redux is based on three core principles: a single source of truth (one global state), the state is read-only (immutable), and changes are made using pure functions (reducers). These principles ensure an orderly and controlled data flow.

function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}
const store = createStore(counterReducer);
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT...

MobX

The next popular solution for managing the global state is the MobX library. This library differs significantly from Redux, with a concept that is in some ways even the opposite.

MobX is a state management library that provides reactive and flexible interaction with data. Its main idea is to make the application state as simple and transparent as possible, working through small objects and classes that can be created as many times as desired and nested within each other.

Technically, the library allows for creating not just one global state but many small objects directly linked to some functionality of the application, which gives a significant advantage when working with large applications. To get the difference between one global state and MobX states, you can look at the following diagram:

Figure 12.5: MobX state

In MobX, the state of the application is managed using observable method, which automatically track changes and inform related computed values...

Summary

In this chapter, we’ve learned about global state and how to manage it. Using the example of limited local state, we’ve discussed why it’s important to have global state in cases where shared data is needed across different components at different levels of the application.

We’ve explored an example using the React Context API and identified when to use it and when to prefer more powerful state management solutions. Next, we looked at two such solutions in the form of Redux and MobX.

In the next chapter, we will discuss server-side rendering and the benefits it can bring to our applications.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127307
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (2)

author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch