Reader small image

You're reading from  Real-World Next.js

Product typeBook
Published inFeb 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801073493
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Michele Riva
Michele Riva
author image
Michele Riva

Michele Riva is a passionate and experienced Software Engineer and Google Developer Expert from Milan, Italy. During the last years, he has contributed to many open-source projects from big companies and foundations, such as Facebook and Apache, in many different programming languages and paradigms, including Haskell, Erlang, Go, and JavaScript. He has also written dozens of public domain articles on different topics (software architecture, functional programming, performance enhancements, etc.) and gave many talks at conferences and meetups. He is currently working as a Senior Software Engineer in the architecture team at ViacomCBS, where he is building a multi-tenant Node.js application at the heart of their websites and streaming services.
Read more about Michele Riva

Right arrow

Chapter 5: Managing Local and Global States in Next.js

State management is one of the central parts of any React application, Next.js apps included. When talking about state, we refer to those dynamic pieces of information that allow us to create highly interactive user interfaces (UIs), making our customers' experience as beautiful and enjoyable as possible.

Thinking about modern websites, we can spot state changes in many parts of the UI: switching from light to dark theme means that we're changing the UI theme state, filling an e-commerce form with our shipping information means that we're changing that form state, even clicking on a simple button can potentially change a local state, as it can lead our UI to react in many different ways, depending on how the developers decided to manage that state update.

Even though state management allows us to create beautiful interactions inside our applications, it comes with some extra complexities. Many developers have...

Technical requirements

To run the code examples in this chapter, you need to have both Node.js and npm installed on your local machine. If you prefer, you can use an online IDE such as https://repl.it or https://codesandbox.io, as they both support Next.js, and you don't need to install any dependency on your computer.

As with the other chapters, you can find the code base for this chapter on GitHub: https://github.com/PacktPublishing/Real-World-Next.js.

Local state management

When talking about local state management, we're referring to application state that is component-scoped. We can summarize that concept with an elementary Counter component:

import React, { useState } from "react";
function Counter({ initialCount = 0 }) {
  const [count, setCount] = useState(initialCount);
  return (
    <div>
      <b>Count is: {count}</b><br />
      <button onClick={() => setCount(count + 1)}>
        Increment +
      </button>
      <button onClick={() => setCount(count - 1)}>
        Decrement -
      </button>
    </div>
  )
}
export default Counter;

When we click...

Global state management

When talking about the global application state, we refer to a state shared between all the components for a given web application that is, therefore, reachable and modifiable by any component.

As seen in the previous section, the React data flow is unidirectional, meaning that components can pass data to their children components, but not to their parents (unlike Vue or Angular). That makes our components less error prone, easier to debug, and more efficient, but adds extra complexity: by default, there cannot be a global state.

Let's take a look at the following scenario:

Figure 5.1 – A link between product cards and items in the cart

In the web application shown in the preceding screenshot, we want to display many products and let our users put them in the shopping cart. The biggest problem here is that there's no link between the data shown in the navigation bar and the product cards, and it can be non-trivial...

Summary

In this chapter, we focused on state management using both React built-in APIs (the Context APIs and Hooks) and external libraries (Redux). There are many other tools and libraries for managing an application's global state (MobX, Recoil, XState, Unistore, to name just a few). You can use all of them inside your Next.js application by initializing them for both client-side and server-side usage, just like we did with Redux.

Also, you can use Apollo GraphQL and its in-memory cache for managing your application state, gaining access to a formal query language for mutating and querying your global data.

We can now create more complex and interactive web applications, managing different kinds of state with any library we want.

But once you have your data well organized and ready to use, you need to display it and render your application UI depending on your application state. In the next chapter, you will see how to style your web app by configuring and using different...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Real-World Next.js
Published in: Feb 2022Publisher: PacktISBN-13: 9781801073493
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

Author (1)

author image
Michele Riva

Michele Riva is a passionate and experienced Software Engineer and Google Developer Expert from Milan, Italy. During the last years, he has contributed to many open-source projects from big companies and foundations, such as Facebook and Apache, in many different programming languages and paradigms, including Haskell, Erlang, Go, and JavaScript. He has also written dozens of public domain articles on different topics (software architecture, functional programming, performance enhancements, etc.) and gave many talks at conferences and meetups. He is currently working as a Senior Software Engineer in the architecture team at ViacomCBS, where he is building a multi-tenant Node.js application at the heart of their websites and streaming services.
Read more about Michele Riva