ホームページ > 記事 > ウェブフロントエンド > React の使用コールバック フックの詳細: ディープ ダイブ
React applications require peak performance, especially as they grow in size and complexity. In our previous article, we explore useMemo, a key hook for memoizing computed values and avoiding unnecessary recalculations. If you are not familiar with useMemo or looking to refresh your understanding, "Understanding React's useMemo" offers valuable insights to enhance your grasp and optimize application efficiency. Checking out this article can provide a solid foundation and practical tips for improving performance.
In this article, we'll focus on useCallback, a sibling hook to useMemo, and explore how it contributes to optimizing your React components. While useMemo is typically used for memoizing function results, useCallback is designed to memoize entire functions. Let's delve into its functionality and how it differs from useMemo.
At its core, useCallback is a React hook that memoizes a function so that the same instance of the function is returned on every render, as long as its dependencies don't change. This can prevent unnecessary function re-creation, which is particularly useful when passing functions as props to child components.
Here’s a basic example:
import React, { useState, useCallback } from 'react'; function Parent() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("Button clicked!"); }, []); return ( <div> <button onClick={handleClick}>Click me</button> <p>You've clicked {count} times</p> </div> ); }
In this example, handleClick is memoized. With no dependencies, it won't be re-created unless the component unmounts. Without useCallback, this function would be recreated on every render, even if its logic remains unchanged.
While useCallback memoizes a function, useMemo memoizes the result of a function's execution. So if you're only concerned with avoiding unnecessary calculations or operations, useMemo might be a better fit. However, if you want to avoid passing a new function reference on every render, useCallback is the tool to use.
import React, { useState, useCallback } from 'react'; function Child({ onClick }) { console.log("Child component rendered"); return <button onClick={onClick}>Click me</button>; } export default function Parent() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("Button clicked!"); }, []); return ( <div> <Child onClick={handleClick} /> <button onClick={() => setCount(count + 1)}>Increase count</button> </div> ); }
Here, the handleClick function is memoized, which prevents the Child component from re-rendering unnecessarily when the parent component's state changes. Without useCallback, the Child component would re-render on every change in the parent, as a new function reference would be passed each time.
In a similar scenario, useMemo would be used if the result of some function logic (not the function itself) needed to be passed to the child. For example, memoizing an expensive calculation to avoid recomputing on every render.
import React, { useState, useCallback } from 'react'; function ListItem({ value, onClick }) { return <li onClick={() => onClick(value)}>{value}</li>; } export default function ItemList() { const [items] = useState([1, 2, 3, 4, 5]); const handleItemClick = useCallback((value) => { console.log("Item clicked:", value); }, []); return ( <ul> {items.map(item => ( <ListItem key={item} value={item} onClick={handleItemClick} /> ))} </ul> ); }
In this scenario, useCallback ensures that the handleItemClick function remains the same across renders, preventing unnecessary re-creation of the function for each list item.
If, instead of passing an event handler, we were calculating the result based on the items (e.g., sum of values in the list), useMemo would be a better fit. useMemo is used to memoize a computed value, while useCallback is strictly for functions.
// Unnecessary use of useCallback const simpleFunction = useCallback(() => { console.log("Simple log"); }, []);
In cases like this, there's no need to memoize the function because there's no dependency or computational overhead.
const handleClick = useCallback(() => { console.log("Clicked with count:", count); }, [count]); // `count` is a dependency here
The memoized function will use stale values if necessary dependencies are omitted, leading to potential bugs.
useCallback 和 useMemo 都是 React 中性能优化的宝贵工具,但它们有不同的用途。当您需要记住昂贵的计算结果时,请使用 useMemo;当您需要确保函数引用在渲染之间保持稳定时,请使用 useCallback。通过了解各自的区别和用例,您可以有效地优化您的 React 应用程序。
要更深入地了解 useMemo,请务必访问此处的完整文章:了解 React 的 useMemo。
以上がReact の使用コールバック フックの詳細: ディープ ダイブの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。