Chapter 5. Common Questions and Powerful Patterns

Now that we’re more aware of what React does and how it works under the hood, let’s explore its practical applications a little deeper in how we write React applications. In this chapter, we’ll explore the answers to common React questions to boost our fluency around memoization, lazy loading, and performance. Let’s get started by talking about memoization.

Memoization with React.memo

Memoization is a technique used in computer science to optimize the performance of functions by caching their previously computed results. In simple terms, memoization stores the output of a function based on its inputs so that if the function is called again with the same inputs, it returns the cached result rather than recomputing the output. This significantly reduces the time and resources needed to execute a function, especially for functions that are computationally expensive or called frequently. Memoization relies on function purity, which is defined as a function predictably returning the same outputs for given inputs. An example of a pure function is:

function add(num1, num2) {
  return num1 + num2;
}

This add function always returns 3 when given arguments 1 and 2, and therefore can be memoized safely. If the function relies on some side effect like network communication, it wouldn’t be memoizable. Consider, for example:

async function addToNumberOfTheDay(num) {
  const todaysNumber = await fetch("https://number-api.com/today")
    .then((r) 

Get Fluent React 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.