diff --git a/src/content/reference/react/useCallback.md b/src/content/reference/react/useCallback.md index 63b36a600..2d2a68eb7 100644 --- a/src/content/reference/react/useCallback.md +++ b/src/content/reference/react/useCallback.md @@ -4,7 +4,7 @@ title: useCallback -`useCallback` is a React Hook that lets you cache a function definition between re-renders. +`useCallback` は、再レンダー間で関数定義をキャッシュできるようにする React フックです。 ```js const cachedFn = useCallback(fn, dependencies) @@ -16,11 +16,11 @@ const cachedFn = useCallback(fn, dependencies) --- -## Reference {/*reference*/} +## リファレンス {/*reference*/} ### `useCallback(fn, dependencies)` {/*usecallback*/} -Call `useCallback` at the top level of your component to cache a function definition between re-renders: +コンポーネントのトップレベルで `useCallback` を呼び出し、再レンダー間で関数定義をキャッシュします。 ```js {4,9} import { useCallback } from 'react'; @@ -34,34 +34,34 @@ export default function ProductPage({ productId, referrer, theme }) { }, [productId, referrer]); ``` -[See more examples below.](#usage) +[さらに例を見る](#usage) -#### Parameters {/*parameters*/} +#### 引数 {/*parameters*/} -* `fn`: The function value that you want to cache. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. On next renders, React will give you the same function again if the `dependencies` have not changed since the last render. Otherwise, it will give you the function that you have passed during the current render, and store it in case it can be reused later. React will not call your function. The function is returned to you so you can decide when and whether to call it. +* `fn`: キャッシュしたい関数型の値。任意の引数を取り、任意の値を返すことができます。React は初回のレンダー時にはその関数をそのまま返します(呼び出しません!)。次回以降のレンダーでは、ひとつ前のレンダー時から `dependencies` が変更されていない場合、React は再び同じ関数を返します。それ以外の場合は、今回のレンダー時に渡された関数を返しつつ、後で再利用できる場合に備えて保存します。React は関数を呼び出しません。関数自体が返されるので、呼ぶか呼ばないか、いつ呼ぶのかについてはあなたが決定できます。 -* `dependencies`: The list of all reactive values referenced inside of the `fn` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. +* `dependencies`: `fn` コード内で参照されるすべてのリアクティブな値のリストです。リアクティブな値には、props、state、コンポーネント本体に直接宣言されたすべての変数および関数が含まれます。リンタが [React 用に設定されている場合](/learn/editor-setup#linting)、すべてのリアクティブな値が依存値として正しく指定されているか確認できます。依存値のリストは要素数が一定である必要があり、`[dep1, dep2, dep3]` のようにインラインで記述する必要があります。React は、[`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) を使った比較で、それぞれの依存値を以前の値と比較します。 -#### Returns {/*returns*/} +#### 返り値 {/*returns*/} -On the initial render, `useCallback` returns the `fn` function you have passed. +初回のレンダー時、`useCallback` は渡された `fn` 関数を返します。 -During subsequent renders, it will either return an already stored `fn` function from the last render (if the dependencies haven't changed), or return the `fn` function you have passed during this render. +その後のレンダー時には、前回のレンダーからすでに保存されている `fn` 関数を返すか(依存配列が変更されていない場合)、このレンダー時に渡された `fn` 関数を返します。 -#### Caveats {/*caveats*/} +#### 注意事項 {/*caveats*/} -* `useCallback` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it. -* React **will not throw away the cached function unless there is a specific reason to do that.** For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache--for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on `useCallback` as a performance optimization. Otherwise, a [state variable](/reference/react/useState#im-trying-to-set-state-to-a-function-but-it-gets-called-instead) or a [ref](/reference/react/useRef#avoiding-recreating-the-ref-contents) may be more appropriate. +* `useCallback` はフックですので、**コンポーネントのトップレベル**または独自のフックでのみ呼び出すことができます。ループや条件の中で呼び出すことはできません。それが必要な場合は、新しいコンポーネントを抽出し、その中にその状態を移動させてください。 +* React は、**特定の理由がない限り、キャッシュされた関数を破棄しません**。たとえば、開発環境では、コンポーネントのファイルを編集すると React はキャッシュを破棄します。開発環境と本番環境の両方で、初回マウント時にコンポーネントがサスペンドすると、React はキャッシュを破棄します。将来的に、React はキャッシュを破棄することを活用したさらなる機能を追加するかもしれません。例えば、将来的に React が仮想化リストに対する組み込みサポートを追加する場合、仮想化されたテーブルのビューポートからスクロールアウトした項目のキャッシュを破棄することが理にかなっています。これは、`useCallback` をパフォーマンスの最適化として利用する場合に期待に沿った動作となります。そうでない場合は、[state 変数](/reference/react/useState#im-trying-to-set-state-to-a-function-but-it-gets-called-instead) や [ref](/reference/react/useRef#avoiding-recreating-the-ref-contents) の方が適切かもしれません。 --- -## Usage {/*usage*/} +## 使い方 {/*usage*/} -### Skipping re-rendering of components {/*skipping-re-rendering-of-components*/} +### コンポーネントの再レンダーをスキップする {/*skipping-re-rendering-of-components*/} -When you optimize rendering performance, you will sometimes need to cache the functions that you pass to child components. Let's first look at the syntax for how to do this, and then see in which cases it's useful. +レンダーのパフォーマンスを最適化する際には、子コンポーネントに渡す関数をキャッシュする必要があることがあります。まずは、これを実現するための構文を見て、その後、どのような場合に便利かを見ていきましょう。 -To cache a function between re-renders of your component, wrap its definition into the `useCallback` Hook: +コンポーネントの再レンダー間で関数をキャッシュするには、その定義を `useCallback` フックでラップします。 ```js [[3, 4, "handleSubmit"], [2, 9, "[productId, referrer]"]] import { useCallback } from 'react'; @@ -76,20 +76,20 @@ function ProductPage({ productId, referrer, theme }) { // ... ``` -You need to pass two things to `useCallback`: +`useCallback` には 2 つの要素を渡す必要があります。 -1. A function definition that you want to cache between re-renders. -2. A list of dependencies including every value within your component that's used inside your function. +1. 再レンダー間でキャッシュしたい関数定義。 +2. 関数内で使用される、コンポーネント内のすべての値を含む依存値のリスト。 -On the initial render, the returned function you'll get from `useCallback` will be the function you passed. +初回のレンダー時に `useCallback` から返される関数、つまりあなたが受け取る関数は、あなたが渡した関数そのものになります。 -On the following renders, React will compare the dependencies with the dependencies you passed during the previous render. If none of the dependencies have changed (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), `useCallback` will return the same function as before. Otherwise, `useCallback` will return the function you passed on *this* render. +次回以降のレンダーでは、React は依存配列を前回のレンダー時に渡した依存配列と比較します。([`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) を使った比較で)依存配列が変更されていない場合、`useCallback` は前回と同じ関数を返します。それ以外の場合、`useCallback` は*今回の*レンダーで渡された関数を返します。 -In other words, `useCallback` caches a function between re-renders until its dependencies change. +言い換えると、`useCallback` は依存配列が変更されるまでの再レンダー間で関数をキャッシュします。 -**Let's walk through an example to see when this is useful.** +**これが有用な場合を例を通じて見ていきましょう**。 -Say you're passing a `handleSubmit` function down from the `ProductPage` to the `ShippingForm` component: +例えば、`ProductPage` から `ShippingForm` コンポーネントに `handleSubmit` 関数を渡しているとします。 ```js {5} function ProductPage({ productId, referrer, theme }) { @@ -101,9 +101,9 @@ function ProductPage({ productId, referrer, theme }) { ); ``` -You've noticed that toggling the `theme` prop freezes the app for a moment, but if you remove `` from your JSX, it feels fast. This tells you that it's worth trying to optimize the `ShippingForm` component. +`theme` プロパティを切り替えるとアプリが一瞬フリーズすることに気付きましたが、JSX から `` を取り除くと、高速に感じられるのだとしましょう。これは `ShippingForm` コンポーネントの最適化を試みる価値があることを示してます。 -**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `ProductPage` re-renders with a different `theme`, the `ShippingForm` component *also* re-renders. This is fine for components that don't require much calculation to re-render. But if you verified a re-render is slow, you can tell `ShippingForm` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](/reference/react/memo) +**デフォルトでは、コンポーネントが再レンダーされると、React はその子要素全てを再帰的に再レンダーします**。これが、`ProductPage` が異なる `theme` で再レンダーされると、`ShippingForm` コンポーネント*も*再レンダーされる理由です。再レンダーに多くの計算を必要としないコンポーネントにとっては問題ありません。しかし、再レンダーが遅いことを確認できたなら、[`memo`](/reference/react/memo) でラップすることで、props が前回のレンダー時と同じである場合に `ShippingForm` に再レンダーをスキップするように指示することができます。 ```js {3,5} import { memo } from 'react'; @@ -113,7 +113,7 @@ const ShippingForm = memo(function ShippingForm({ onSubmit }) { }); ``` -**With this change, `ShippingForm` will skip re-rendering if all of its props are the *same* as on the last render.** This is when caching a function becomes important! Let's say you defined `handleSubmit` without `useCallback`: +**この変更により、すべての props が前回のレンダー時と*同じ*場合、`ShippingForm` は再レンダーをスキップするようになります**。ここで関数のキャッシュが重要になってきます! `handleSubmit` を `useCallback` なしで定義したとしましょう。 ```js {2,3,8,12-13} function ProductPage({ productId, referrer, theme }) { @@ -134,7 +134,7 @@ function ProductPage({ productId, referrer, theme }) { } ``` -**In JavaScript, a `function () {}` or `() => {}` always creates a _different_ function,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn't be a problem, but it means that `ShippingForm` props will never be the same, and your [`memo`](/reference/react/memo) optimization won't work. This is where `useCallback` comes in handy: +**JavaScript では、`function () {}` または `() => {}` は常に*異なる*関数を作成します**。これは `{}` のオブジェクトリテラルが常に新しいオブジェクトを作成するのと似ています。通常、これは問題になりませんが、`ShippingForm` の props が決して同じにならないので [`memo`](/reference/react/memo) による最適化は機能しなくなるということでもあります。このようなときに有用になってくるのが `useCallback` です。 ```js {2,3,8,12-13} function ProductPage({ productId, referrer, theme }) { @@ -155,19 +155,19 @@ function ProductPage({ productId, referrer, theme }) { } ``` -**By wrapping `handleSubmit` in `useCallback`, you ensure that it's the *same* function between the re-renders** (until dependencies change). You don't *have to* wrap a function in `useCallback` unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in [`memo`,](/reference/react/memo) and this lets it skip re-rendering. There are other reasons you might need `useCallback` which are described further on this page. +**`handleSubmit` を `useCallback` でラップすることで、再レンダー間でそれを*同一の*関数にすることができます**(依存配列が変更されるまで)。それをする特定の理由がない限り、関数を `useCallback` でラップする*必要はありません*。今回の例における理由とは、この関数を [`memo`](/reference/react/memo) でラップされたコンポーネントに渡せば再レンダーをスキップできるということです。このページの後半で説明されているように、`useCallback` が必要な他の理由もあります。 -**You should only rely on `useCallback` as a performance optimization.** If your code doesn't work without it, find the underlying problem and fix it first. Then you may add `useCallback` back. +**`useCallback` はパフォーマンスの最適化としてのみ用いるべきです**。もしコードがそれなしでは動作しない場合は、背後にある問題を見つけてまずそれを修正してください。その後、`useCallback` を再度追加することができます。 -#### How is useCallback related to useMemo? {/*how-is-usecallback-related-to-usememo*/} +#### useCallback と useMemo の関係 {/*how-is-usecallback-related-to-usememo*/} -You will often see [`useMemo`](/reference/react/useMemo) alongside `useCallback`. They are both useful when you're trying to optimize a child component. They let you [memoize](https://en.wikipedia.org/wiki/Memoization) (or, in other words, cache) something you're passing down: +`useCallback` と並んで [`useMemo`](/reference/react/useMemo) をよく見かけることでしょう。子コンポーネントを最適化しようとするとき、どちらも有用です。これらはあなたが下位に渡している何かを[メモ化する (memoize)](https://en.wikipedia.org/wiki/Memoization)(言い換えると、キャッシュする)ことを可能にします。 ```js {6-8,10-15,19} import { useMemo, useCallback } from 'react'; @@ -194,12 +194,12 @@ function ProductPage({ productId, referrer }) { } ``` -The difference is in *what* they're letting you cache: +その違いはキャッシュできる*内容*です。 -* **[`useMemo`](/reference/react/useMemo) caches the *result* of calling your function.** In this example, it caches the result of calling `computeRequirements(product)` so that it doesn't change unless `product` has changed. This lets you pass the `requirements` object down without unnecessarily re-rendering `ShippingForm`. When necessary, React will call the function you've passed during rendering to calculate the result. -* **`useCallback` caches *the function itself.*** Unlike `useMemo`, it does not call the function you provide. Instead, it caches the function you provided so that `handleSubmit` *itself* doesn't change unless `productId` or `referrer` has changed. This lets you pass the `handleSubmit` function down without unnecessarily re-rendering `ShippingForm`. Your code won't run until the user submits the form. +* **[`useMemo`](/reference/react/useMemo) はあなたの関数の呼び出し*結果*をキャッシュします**。この例では、`product` が変更されない限り、`computeRequirements(product)` の呼び出し結果をキャッシュします。これにより、`ShippingForm` を不必要に再レンダーすることなく、`requirements` オブジェクトを下位に渡すことができます。必要に応じて、React はレンダー中にあなたが渡した関数を呼び出して結果を計算します。 +* **`useCallback` は*関数自体*をキャッシュします**。`useMemo`とは異なり、あなたが提供する関数を呼び出しません。代わりに、あなたが提供した関数をキャッシュして、`productId` または `referrer` が変更されない限り、`handleSubmit` *自体*が変更されないようにします。これにより、`ShippingForm` を不必要に再レンダーすることなく、`handleSubmit` 関数を下位に渡すことができます。ユーザーがフォームを送信するまであなたのコードは実行されません。 -If you're already familiar with [`useMemo`,](/reference/react/useMemo) you might find it helpful to think of `useCallback` as this: +すでに [`useMemo`](/reference/react/useMemo) に詳しい場合、`useCallback` を次のように考えると役立つかもしれません。 ```js // Simplified implementation (inside React) @@ -208,46 +208,46 @@ function useCallback(fn, dependencies) { } ``` -[Read more about the difference between `useMemo` and `useCallback`.](/reference/react/useMemo#memoizing-a-function) +[`useMemo` と `useCallback` の違いについてもっと読む](/reference/react/useMemo#memoizing-a-function) -#### Should you add useCallback everywhere? {/*should-you-add-usecallback-everywhere*/} +#### すべてに useCallback を追加すべきか? {/*should-you-add-usecallback-everywhere*/} -If your app is like this site, and most interactions are coarse (like replacing a page or an entire section), memoization is usually unnecessary. On the other hand, if your app is more like a drawing editor, and most interactions are granular (like moving shapes), then you might find memoization very helpful. +あなたのアプリがこのサイトのように、ほとんどのインタラクションが大まかなもの(ページ全体やセクション全体の置き換えなど)である場合、メモ化は通常不要です。一方、あなたのアプリが描画エディターのようなもので、ほとんどのインタラクションが細かい(形状の移動など)場合、メモ化は非常に役立つかもしれません。 -Caching a function with `useCallback` is only valuable in a few cases: +`useCallback` で関数をキャッシュすることが有用なのはいくつかのケースに限られます。 -- You pass it as a prop to a component wrapped in [`memo`.](/reference/react/memo) You want to skip re-rendering if the value hasn't changed. Memoization lets your component re-render only if dependencies changed. -- The function you're passing is later used as a dependency of some Hook. For example, another function wrapped in `useCallback` depends on it, or you depend on this function from [`useEffect.`](/reference/react/useEffect) +- それを [`memo`](/reference/react/memo) でラップされたコンポーネントに props として渡すケース。値が変わらないなら再レンダーをスキップしたいことでしょう。メモ化により、依存配列が変更された場合にのみ、コンポーネントが再レンダーされるようになります。 +- あなたが渡している関数が、後で何らかのフックの依存値として使用されるケース。たとえば、他の `useCallback` でラップされた関数がそれに依存している、または [`useEffect`](/reference/react/useEffect) からこの関数に依存しているケースです。 -There is no benefit to wrapping a function in `useCallback` in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside is that code becomes less readable. Also, not all memoization is effective: a single value that's "always new" is enough to break memoization for an entire component. +その他のケースで関数を `useCallback` でラップする利点はありません。それを行っても重大な害はないため、一部のチームは個々のケースについて考えず、可能な限り多くをメモ化することを選択します。欠点は、コードが読みにくくなることです。また、すべてのメモ化が効果的なわけではありません。「毎回新しい」値がひとつあるだけで、コンポーネントのメモ化は全く機能しなくなってしまいます。 -Note that `useCallback` does not prevent *creating* the function. You're always creating a function (and that's fine!), but React ignores it and gives you back a cached function if nothing changed. +`useCallback` は関数の*作成*を防ぐわけではないことに注意してください。あなたは常に関数を作成しています(それは問題ありません!)。しかし、何も変わらない場合、React はそれを無視し、キャッシュされた関数を返します。 -**In practice, you can make a lot of memoization unnecessary by following a few principles:** +**実際には、以下のいくつかの原則に従うことで、多くのメモ化を不要にすることができます**。 -1. When a component visually wraps other components, let it [accept JSX as children.](/learn/passing-props-to-a-component#passing-jsx-as-children) Then, if the wrapper component updates its own state, React knows that its children don't need to re-render. -1. Prefer local state and don't [lift state up](/learn/sharing-state-between-components) any further than necessary. Don't keep transient state like forms and whether an item is hovered at the top of your tree or in a global state library. -1. Keep your [rendering logic pure.](/learn/keeping-components-pure) If re-rendering a component causes a problem or produces some noticeable visual artifact, it's a bug in your component! Fix the bug instead of adding memoization. -1. Avoid [unnecessary Effects that update state.](/learn/you-might-not-need-an-effect) Most performance problems in React apps are caused by chains of updates originating from Effects that cause your components to render over and over. -1. Try to [remove unnecessary dependencies from your Effects.](/learn/removing-effect-dependencies) For example, instead of memoization, it's often simpler to move some object or a function inside an Effect or outside the component. +1. コンポーネントが他のコンポーネントを視覚的にラップするときは、それが[子として JSX を受け入れるようにします](/learn/passing-props-to-a-component#passing-jsx-as-children)。これにより、ラッパコンポーネントが自身の state を更新しても、React はその子を再レンダーする必要がないことを認識します。 +1. ローカル state を優先し、必要以上に [state のリフトアップ](/learn/sharing-state-between-components)を行わないようにします。フォームや、アイテムがホバーされているかどうかのような頻繁に変わる state を、ツリーのトップやグローバル状態ライブラリに保持しないでください。 +1. [レンダーロジックを純粋に](/learn/keeping-components-pure)保ちます。コンポーネントの再レンダーが問題を引き起こしたり、何らかの目に見える視覚的な結果を生じたりする場合、それはあなたのコンポーネントのバグです! メモ化を追加するのではなく、バグを修正します。 +1. [state を更新する不要なエフェクトを避けてください](/learn/you-might-not-need-an-effect)。React アプリケーションのパフォーマンス問題の大部分は、エフェクト内での連鎖的な state 更新によってコンポーネントのレンダーが何度も引き起こされるために生じます。 +1. [エフェクトから不要な依存値をできるだけ削除します](/learn/removing-effect-dependencies)。例えば、メモ化の代わりに、あるオブジェクトや関数をエフェクトの内側、あるいはコンポーネント外部に移動させる方が簡単なことがよくあります。 -If a specific interaction still feels laggy, [use the React Developer Tools profiler](https://legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html) to see which components benefit the most from memoization, and add memoization where needed. These principles make your components easier to debug and understand, so it's good to follow them in any case. In long term, we're researching [doing memoization automatically](https://www.youtube.com/watch?v=lGEMwh32soc) to solve this once and for all. +特定のインタラクションの遅延をまだ感じる場合は、[React Developer Tools のプロファイラを使用して](https://legacy.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html)どのコンポーネントをメモ化することが最も有益か確認し、必要な場所にメモ化を追加してください。上記の原則に従うことでコンポーネントのデバッグと理解が容易になるため、いかなる場合でも従っておくことは良いことです。長期的には、この問題を一挙に解決できる[自動的なメモ化](https://www.youtube.com/watch?v=lGEMwh32soc)について研究を行っています。 - + -#### Skipping re-rendering with `useCallback` and `memo` {/*skipping-re-rendering-with-usecallback-and-memo*/} +#### `useCallback` と `memo` を使用して再レンダーをスキップする {/*skipping-re-rendering-with-usecallback-and-memo*/} -In this example, the `ShippingForm` component is **artificially slowed down** so that you can see what happens when a React component you're rendering is genuinely slow. Try incrementing the counter and toggling the theme. +この例では、`ShippingForm` コンポーネントを**人為的に遅く**しているため、あなたがレンダーしている React コンポーネントが本当に遅いときに何が起こるかを見ることができます。カウンタを増加させたり、テーマを切り替えたりしてみてください。 -Incrementing the counter feels slow because it forces the slowed down `ShippingForm` to re-render. That's expected because the counter has changed, and so you need to reflect the user's new choice on the screen. +カウンタの増加は遅く感じられますが、これは低速な `ShippingForm` を再レンダーせざるを得ないからです。カウンタが変更され、ユーザが行った選択を画面上に反映する必要があるのですから、これ自体は予想通りの動作です。 -Next, try toggling the theme. **Thanks to `useCallback` together with [`memo`](/reference/react/memo), it’s fast despite the artificial slowdown!** `ShippingForm` skipped re-rendering because the `handleSubmit` function has not changed. The `handleSubmit` function has not changed because both `productId` and `referrer` (your `useCallback` dependencies) haven't changed since last render. +次に、テーマを切り替えてみてください。**人為的に遅くしているにも関わらず、`useCallback` と [`memo`](/reference/react/memo) を組み合わせたおかげで高速に動作しています**! `ShippingForm` は、`handleSubmit` 関数が変更されていないため、再レンダーをスキップしました。`handleSubmit` 関数は変更されていません。なぜなら、`productId` と `referrer`(あなたの `useCallback` の依存値)のいずれも、最後のレンダー以降に変更されていないからです。 @@ -383,11 +383,11 @@ button[type="button"] { -#### Always re-rendering a component {/*always-re-rendering-a-component*/} +#### 常にコンポーネントを再レンダーする {/*always-re-rendering-a-component*/} -In this example, the `ShippingForm` implementation is also **artificially slowed down** so that you can see what happens when some React component you're rendering is genuinely slow. Try incrementing the counter and toggling the theme. +この例でも、`ShippingForm` の実装を**人為的に遅く**してあり、レンダーしている React コンポーネントが本当に遅いときに何が起こるかを見ることができます。カウンタを増加させたり、テーマを切り替えたりしてみてください。 -Unlike in the previous example, toggling the theme is also slow now! This is because **there is no `useCallback` call in this version,** so `handleSubmit` is always a new function, and the slowed down `ShippingForm` component can't skip re-rendering. +前の例とは異なり、今度はテーマの切り替えも低速です! これは、**このバージョンには `useCallback` の呼び出しがないため**、`handleSubmit` は常に新しい関数であり、遅くなっている `ShippingForm` コンポーネントの再レンダーをスキップできないからです。 @@ -521,7 +521,7 @@ button[type="button"] { -However, here is the same code **with the artificial slowdown removed.** Does the lack of `useCallback` feel noticeable or not? +しかし、以下は**人為的な遅さを取り除いた**同じコードです。`useCallback` が無いことに、気づくほどの影響があるでしょうか? @@ -650,9 +650,9 @@ button[type="button"] { -Quite often, code without memoization works fine. If your interactions are fast enough, you don't need memoization. +かなりの頻度で、メモ化なしのコードでも問題なく動作します。あなたのインタラクションが十分に速い場合、メモ化は必要ありません。 -Keep in mind that you need to run React in production mode, disable [React Developer Tools](/learn/react-developer-tools), and use devices similar to the ones your app's users have in order to get a realistic sense of what's actually slowing down your app. +あなたのアプリが遅くなっている真の理由を把握するためには、React を本番モードで実行し、[React Developer Tools](/learn/react-developer-tools) を無効にし、あなたのアプリのユーザが使用しているデバイスと同様のデバイスを使用する必要があることに留意してください。 @@ -660,11 +660,11 @@ Keep in mind that you need to run React in production mode, disable [React Devel --- -### Updating state from a memoized callback {/*updating-state-from-a-memoized-callback*/} +### メモ化されたコールバックからの state 更新 {/*updating-state-from-a-memoized-callback*/} -Sometimes, you might need to update state based on previous state from a memoized callback. +場合によっては、メモ化されたコールバックから前回の state に基づいて state を更新する必要があります。 -This `handleAddTodo` function specifies `todos` as a dependency because it computes the next todos from it: +この `handleAddTodo` 関数は、次の todo リストを計算するために `todos` を依存値として指定します。 ```js {6,7} function TodoList() { @@ -677,7 +677,7 @@ function TodoList() { // ... ``` -You'll usually want memoized functions to have as few dependencies as possible. When you read some state only to calculate the next state, you can remove that dependency by passing an [updater function](/reference/react/useState#updating-state-based-on-the-previous-state) instead: +通常、メモ化された関数からは可能な限り依存値を少なくしたいと思うでしょう。何らかの state を次の state を計算するためだけに読み込んでいる場合、代わりに[更新用関数 (updater function)](/reference/react/useState#updating-state-based-on-the-previous-state) を渡すことでその依存値を削除できます。 ```js {6,7} function TodoList() { @@ -690,13 +690,13 @@ function TodoList() { // ... ``` -Here, instead of making `todos` a dependency and reading it inside, you pass an instruction about *how* to update the state (`todos => [...todos, newTodo]`) to React. [Read more about updater functions.](/reference/react/useState#updating-state-based-on-the-previous-state) +ここでは、`todos` を依存値として内部で読み込む代わりに、*どのように* state を更新するかについての指示(`todos => [...todos, newTodo]`)を React に渡します。[更新用関数についての詳細はこちら](/reference/react/useState#updating-state-based-on-the-previous-state)。 --- -### Preventing an Effect from firing too often {/*preventing-an-effect-from-firing-too-often*/} +### エフェクトが頻繁に発火するのを防ぐ {/*preventing-an-effect-from-firing-too-often*/} -Sometimes, you might want to call a function from inside an [Effect:](/learn/synchronizing-with-effects) +時々、[エフェクト](/learn/synchronizing-with-effects) の内部から関数を呼び出したいことがあるかもしれません。 ```js {4-9,12} function ChatRoom({ roomId }) { @@ -716,7 +716,7 @@ function ChatRoom({ roomId }) { // ... ``` -This creates a problem. [Every reactive value must be declared as a dependency of your Effect.](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency) However, if you declare `createOptions` as a dependency, it will cause your Effect to constantly reconnect to the chat room: +これには問題があります。[全てのリアクティブな値はエフェクトの依存値として宣言されなければなりません](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency)。しかし、`createOptions` を依存値として宣言すると、あなたのエフェクトがチャットルームに常に再接続することになります。 ```js {6} @@ -729,7 +729,7 @@ This creates a problem. [Every reactive value must be declared as a dependency o // ... ``` -To solve this, you can wrap the function you need to call from an Effect into `useCallback`: +これを解決するために、エフェクトから呼び出す必要がある関数を `useCallback` でラップすることができます。 ```js {4-9,16} function ChatRoom({ roomId }) { @@ -751,7 +751,7 @@ function ChatRoom({ roomId }) { // ... ``` -This ensures that the `createOptions` function is the same between re-renders if the `roomId` is the same. **However, it's even better to remove the need for a function dependency.** Move your function *inside* the Effect: +これにより、`roomId` が同じ場合に再レンダー間で `createOptions` 関数が同じであることが保証されます。**しかし、関数型の依存値を必要としないようにする方がさらに望ましいでしょう**。関数をエフェクトの*内部*に移動します。 ```js {5-10,16} function ChatRoom({ roomId }) { @@ -773,13 +773,13 @@ function ChatRoom({ roomId }) { // ... ``` -Now your code is simpler and doesn't need `useCallback`. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect) +これでコードはよりシンプルになり、`useCallback` が不要になりました。[エフェクトの依存値の削除についてさらに学ぶ](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)。 --- -### Optimizing a custom Hook {/*optimizing-a-custom-hook*/} +### カスタムフックの最適化 {/*optimizing-a-custom-hook*/} -If you're writing a [custom Hook,](/learn/reusing-logic-with-custom-hooks) it's recommended to wrap any functions that it returns into `useCallback`: +あなたが[カスタムフック](/learn/reusing-logic-with-custom-hooks)を書いている場合、それが返すあらゆる関数は `useCallback` でラップすることが推奨されます。 ```js {4-6,8-10} function useRouter() { @@ -800,17 +800,17 @@ function useRouter() { } ``` -This ensures that the consumers of your Hook can optimize their own code when needed. +これにより、フックを利用する側が必要に応じて自身のコードを最適化することができます。 --- -## Troubleshooting {/*troubleshooting*/} +## トラブルシューティング {/*troubleshooting*/} -### Every time my component renders, `useCallback` returns a different function {/*every-time-my-component-renders-usecallback-returns-a-different-function*/} +### コンポーネントがレンダーするたびに `useCallback` が異なる関数を返す {/*every-time-my-component-renders-usecallback-returns-a-different-function*/} -Make sure you've specified the dependency array as a second argument! +第 2 引数として依存配列を指定したかを確認してください! -If you forget the dependency array, `useCallback` will return a new function every time: +依存配列を忘れると、`useCallback` は毎回新しい関数を返します。 ```js {7} function ProductPage({ productId, referrer }) { @@ -823,7 +823,7 @@ function ProductPage({ productId, referrer }) { // ... ``` -This is the corrected version passing the dependency array as a second argument: +以下は、第 2 引数として依存配列を渡す修正版です。 ```js {7} function ProductPage({ productId, referrer }) { @@ -836,7 +836,7 @@ function ProductPage({ productId, referrer }) { // ... ``` -If this doesn't help, then the problem is that at least one of your dependencies is different from the previous render. You can debug this problem by manually logging your dependencies to the console: +これでもうまくいかない場合、問題は、少なくとも 1 つの依存値が前回のレンダーと異なることです。依存値を手動でコンソールにログ出力することで、この問題をデバッグできます。 ```js {5} const handleSubmit = useCallback((orderDetails) => { @@ -846,7 +846,7 @@ If this doesn't help, then the problem is that at least one of your dependencies console.log([productId, referrer]); ``` -You can then right-click on the arrays from different re-renders in the console and select "Store as a global variable" for both of them. Assuming the first one got saved as `temp1` and the second one got saved as `temp2`, you can then use the browser console to check whether each dependency in both arrays is the same: +その後、コンソール内の異なる再レンダーからの配列を右クリックすると、それぞれに対して「グローバル変数として保存」が選択できます。最初のものが `temp1` として、2 つ目が `temp2` として保存されたと仮定すると、ブラウザのコンソールを使用して、両方の配列内の各依存値が同一であるかどうかを以下のように確認できます。 ```js Object.is(temp1[0], temp2[0]); // Is the first dependency the same between the arrays? @@ -854,13 +854,13 @@ Object.is(temp1[1], temp2[1]); // Is the second dependency the same between the Object.is(temp1[2], temp2[2]); // ... and so on for every dependency ... ``` -When you find which dependency is breaking memoization, either find a way to remove it, or [memoize it as well.](/reference/react/useMemo#memoizing-a-dependency-of-another-hook) +メモ化を壊している依存値を見つけたら、それを取り除く方法を見つけるか、または[それもメモ化します。](/reference/react/useMemo#memoizing-a-dependency-of-another-hook) --- -### I need to call `useCallback` for each list item in a loop, but it's not allowed {/*i-need-to-call-usememo-for-each-list-item-in-a-loop-but-its-not-allowed*/} +### ループ内の各リスト要素で `useCallback` を呼び出す必要があるが、それは許されていない {/*i-need-to-call-usememo-for-each-list-item-in-a-loop-but-its-not-allowed*/} -Suppose the `Chart` component is wrapped in [`memo`](/reference/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can't call `useCallback` in a loop: +`Chart` コンポーネントが [`memo`](/reference/react/memo) でラップされていると仮定します。`ReportList` コンポーネントが再レンダーするときに、リスト内の `Chart` がすべて再レンダーされてしまわないよう、一部をスキップしたいとしましょう。しかし、ループの中で `useCallback` を呼び出すことはできません。 ```js {5-14} function ReportList({ items }) { @@ -883,7 +883,7 @@ function ReportList({ items }) { } ``` -Instead, extract a component for an individual item, and put `useCallback` there: +代わりに、個々のアイテムに対応するコンポーネントを抽出し、その中に `useCallback` を配置します。 ```js {5,12-21} function ReportList({ items }) { @@ -910,7 +910,7 @@ function Report({ item }) { } ``` -Alternatively, you could remove `useCallback` in the last snippet and instead wrap `Report` itself in [`memo`.](/reference/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too: +もしくは、最後のスニペットから `useCallback` を削除し、代わりに `Report` 自体を [`memo`](/reference/react/memo) でラップすることもできます。`item` プロパティが変更されない場合、`Report` は再レンダーをスキップするため、`Chart` も再レンダーをスキップします。 ```js {5,6-8,15} function ReportList({ items }) {