Chapter 3. Managing State

When we manage state in React, we have to store data, but we also record data dependencies. Dependencies are intrinsic to the way that React works. They allow React to update the page efficiently and only when necessary.

Managing data dependencies, then, is the key to managing state in React. You will see throughout this chapter that most of the tools and techniques we use are to ensure that we manage dependencies efficiently.

A key concept in the following recipes is a data reducer. A reducer is simply a function that receives a single object or an array and then returns a modified copy. This simple concept is what lies behind much of the state management in React. We’ll look at how React uses reducer functions natively and how we can use the Redux library to manage data application-wide with reducers.

We’ll also look at selector functions. These allow us to drill into the state returned by reducers. Selectors help us ignore the irrelevant data, and in doing so, they significantly improve the performance of our code.

Along the way, we’ll look at simple ways of checking whether you’re online, how to manage form data, and various other tips and tricks to keep your application ticking along.

3.1 Use Reducers to Manage Complex State

Problem

Many React components are straightforward. They do little more than render a section of HTML and perhaps show a few properties.

However, some components can be more complicated. They might need to manage several pieces ...

Get React Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.