Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
React and React Native - Fifth Edition

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

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781805127307
Pages 508 pages
Edition 5th Edition
Languages
Authors (2):
Mikhail Sakhniuk Mikhail Sakhniuk
Profile icon Mikhail Sakhniuk
Adam Boduch Adam Boduch
Profile icon Adam Boduch
View More author details

Table of Contents (33) Chapters

Preface 1. Part I: React
2. Why React? 3. Rendering with JSX 4. Understanding React Components and Hooks 5. Event Handling in the React Way 6. Crafting Reusable Components 7. Type-Checking and Validation with TypeScript 8. Handling Navigation with Routes 9. Code Splitting Using Lazy Components and Suspense 10. User Interface Framework Components 11. High-Performance State Updates 12. Fetching Data from a Server 13. State Management in React 14. Server-Side Rendering 15. Unit Testing in React 16. Part II: React Native
17. Why React Native? 18. React Native under the Hood 19. Kick-Starting React Native Projects 20. Building Responsive Layouts with Flexbox 21. Navigating Between Screens 22. Rendering Item Lists 23. Geolocation and Maps 24. Collecting User Input 25. Responding to User Gestures 26. Showing Progress 27. Displaying Modal Screens 28. Using Animations 29. Controlling Image Display 30. Going Offline 31. Other Books You May Enjoy
32. Index

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 2024 Publisher: Packt ISBN-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.
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}