iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝

The "Standard" Way to Write React Components Isn't Actually Guaranteed

に公開
2026/02/21
4件

Introduction

When writing a component in React, you probably write it like this:

function Greeting({ name }) {
  return <p>Hello, {name}!</p>;
}

You receive props and return JSX. I imagine you do this without thinking much, thinking, "This is just how you write it."

However, behind this "normal" practice lies a rule that React relies on with all its might.

That rule is Purity.

It is because of this rule that React.memo can safely skip rendering, Server Components can handle multiple user requests simultaneously, and Concurrent Mode can discard rendering in progress.

You might be following it naturally. But it is also possible to break it without realizing it. Today, we are talking about this "incredibly important rule that you use without knowing."

What is Purity?

The rule itself is simple.

  1. Return the same output for the same input
  2. Do not mutate variables outside the scope

A function that satisfies these two is called a "pure function." And React operates under the assumption that every component is a pure function.

Let's look at this concretely.

Bad Example: An Impure Component

let likeCount = 0;

function LikeButton() {
  likeCount += 1; // Mutating a variable outside the scope
  return <button>♡ {likeCount}</button>;
}

The result of this component changes every time it is called. If you align <LikeButton /> three times, you get ♡ 1, ♡ 2, ♡ 3. Even though the input (no props) is the same, the output is different every time. This is not pure.

Good Example: A Pure Component

function LikeButton({ count }) {
  return <button>♡ {count}</button>;
}

If you pass count={5}, it will always return ♡ 5. No matter how many times you call it, it is the same. This is pure.

By the way, it is perfectly fine to mutate variables you created on the spot during rendering (local mutation). Since it doesn't affect the outside, it's fine.

function LikeButtons() {
  const buttons = [];
  for (let i = 1; i <= 5; i++) {
    buttons.push(<LikeButton key={i} count={i} />); // buttons was created within this function -> OK
  }
  return buttons;
}

"No matter when, where, or who calls it, the result is always the same."
This is the core of purity.

The Main Topic: What Breaks Without This "Common Sense"?

"I understand the rule. So, why is it so important?"

It is important. React's core features are built upon this purity. Let's look at them specifically.

1. Memoization can be done "safely"

React.memo is a mechanism where "if the props are the same as before, skip rendering and reuse the previous result."

This works because components are pure.

  • Pure -> Same input always results in the same output
  • In other words, if props haven't changed, the result is guaranteed to be the same
  • Therefore, it is safe to skip the calculation

(Strictly speaking, React has three "inputs": props, state, and context, but since you have to re-render anyway if state or context changes, React.memo only needs to consider props.)

What happens if it isn't pure?

function Greeting({ name }) {
  const hour = new Date().getHours();
  if (hour < 12) {
    return <p>Good morning, {name}!</p>;
  }
  return <p>Hello, {name}!</p>;
}

Even if the name prop is the same, the result changes if the time changes. If you skip it with React.memo, the "Good morning" displayed in the morning won't update even when it becomes afternoon. The cache becomes untrustworthy.

It is precisely because it is pure that we can definitively say "same input = same result" and safely slack off. This is the foundation of memoization.

2. Can be safely reused on the server

Many of you are likely using Next.js Server Components. Server Components are a mechanism that renders components on the server side and sends the result to the client as an RSC Payload (React Server Component Payload).

On the server, requests from multiple users are processed simultaneously. If a component were not pure—

let requestCount = 0;

function Page() {
  requestCount += 1;
  return <div>Request #{requestCount}</div>;
}

User A's request would result in #1, and User B's would be #2. It would interfere with other users' requests.

If the component is pure, it always returns the same result for the same props, so it is safe to execute regardless of whose request it is. There is no need to worry about components interfering with each other.

The reason we can use Server Components in Next.js as a matter of course is because this purity is a prerequisite.

3. Rendering can be discarded mid-way

React has a mechanism called "Concurrent Mode." Simply put, it is a system that allows React to say, "Oh, new data has arrived. The current calculation is already old, so let's discard it."

This is also only possible because of purity.

Pure components do not have any impact on the outside world during rendering. Therefore, even if you discard the result calculated halfway through, it is "as if nothing happened."

Because it is pure, it can safely be interrupted and retried.

Conclusion

Let's reflect on React's purity.

React Feature What happens without purity?
React.memo Cache cannot be trusted
Server Components Requests interfere across users
Concurrent Mode Side effects remain if interrupted mid-way

"Write components purely"—this is not just a stylistic rule. By assuming purity, React makes it possible to perform caching, server execution, and rendering interruption safely and efficiently.

That way of writing you do because "this is just how you write it" is actually supporting React's strengths. Knowing what lies within that "common sense" might just make you like React's design a little bit more.

Discussion

しぐれ煮しぐれ煮

Next.jsのServer Componentsを使っている方は多いと思います。サーバー側でコンポーネントをレンダリングしてHTMLを返す仕組みですね。

ではないです。HTMLではなくJSONを返す仕組みです。また、サーバを使用しません。

1
あさひあさひ

ご指摘ありがとうございます。

おっしゃる通り、Server Componentsが生成するのはHTMLではなくRSC Payload(React Server Component Payload)で、HTMLへの変換はSSRが担当する別のステップですね。「Server ComponentsがレンダリングしてHTMLを返す」という表現はこの2つを混同していました。記事の該当箇所を修正します。

サーバの使用についても、React仕様としてはビルド時実行も可能なので「サーバ側で」という表現が不正確な点、理解しました。記事ではNext.jsの文脈で書いていましたが、より正確な表現に改めます。

Server Componentsの内部的な仕組みについてはまだ理解が浅く、これから深掘りしていきたいと思っていたところなので、リンクも含めとても勉強になりました。ありがとうございます。

1
しぐれ煮しぐれ煮

この2つを満たす関数を 「純関数」 と呼びます。そしてReactは、すべてのコンポーネントが純関数であるという前提で動いています。

外部のファイルやデータベースの値を読み取るといった「実行する度に値が変わる可能性のある関数」についてはどう考えますか?

https://ja.react.dev/reference/rsc/server-components

これは公式の資料に書かれていたサンプルのコードです。

import db from './database';

async function Note({id}) {
  // NOTE: loads *during* render.
  const note = await db.notes.get(id);
  return (
    <div>
      <Author id={note.authorId} />
      <p>{note}</p>
    </div>
  );
}

async function Author({id}) {
  // NOTE: loads *after* Note,
  // but is fast if data is co-located.
  const author = await db.authors.get(id);
  return <span>By: {author.name}</span>;
}

この関数たちは以下の2つを満たしていません。

  • 同じ入力には、同じ出力を返す
  • スコープ外の変数を変更(ミューテート)しない

これはダメな例に該当しますか?

あさひあさひ

コメントありがとうございます。

ご指摘の通り、Server Componentsでデータベースを読むコンポーネントは厳密な意味での純関数ではありません。同じidを渡しても、DBの値が更新されれば出力が変わります。

この記事はReact公式のKeeping Components Pureをベースにしており、クライアント側のレンダリングサイクルにおける純粋性の話です。React.memoのスキップやConcurrent Modeの中断が安全に動くために「同じ入力→同じ出力」が必要になる、という文脈です。

Server Componentsはサーバー上で1リクエストにつき1回実行され、クライアント側のレンダリングサイクルには参加しないため、ここでの純粋性の議論とは適用範囲が異なるかと考えています。

本件のデータ取得と純粋性の関係を含め、Server Componentsについては、それだけで記事にできるだけの興味深いテーマだと思っているので、別の記事で改めて扱う予定です。

記事中にスコープの補足がなくわかりづらかった点は改善します。ありがとうございます。

1