Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Real-World Next.js

You're reading from  Real-World Next.js

Product type Book
Published in Feb 2022
Publisher Packt
ISBN-13 9781801073493
Pages 366 pages
Edition 1st Edition
Languages
Author (1):
Michele Riva Michele Riva
Profile icon Michele Riva

Table of Contents (19) Chapters

Preface 1. Part 1: Introduction to Next.js
2. Chapter 1: A Brief Introduction to Next.js 3. Chapter 2: Exploring Different Rendering Strategies 4. Chapter 3: Next.js Basics and Built-In Components 5. Part 2: Hands-On Next.js
6. Chapter 4: Organizing the Code Base and Fetching Data in Next.js 7. Chapter 5: Managing Local and Global States in Next.js 8. Chapter 6: CSS and Built-In Styling Methods 9. Chapter 7: Using UI Frameworks 10. Chapter 8: Using a Custom Server 11. Chapter 9: Testing Next.js 12. Chapter 10: Working with SEO and Managing Performance 13. Chapter 11: Different Deployment Platforms 14. Part 3: Next.js by Example
15. Chapter 12: Managing Authentication and User Sessions 16. Chapter 13: Building an E-Commerce Website with Next.js and GraphCMS 17. Chapter 14: Example Projects and Next Steps for Learning More 18. Other Books You May Enjoy

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 2022 Publisher: Packt ISBN-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.
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 $15.99/month. Cancel anytime}