乐闻世界logo
搜索文章和话题

What is useCallback in React and when to use it?

1个答案

1

useCallback is a React Hook primarily used to optimize performance in components. By memoizing a function, it prevents unnecessary re-creation during component re-renders, thereby reducing the overhead associated with component re-renders.

What is the Purpose of useCallback?

  1. Avoiding Unnecessary Re-renders: useCallback returns a memoized version of the callback function that updates only when elements in the dependency array change. This prevents unnecessary re-creation of the function during the render cycle, reducing unnecessary re-renders of child components triggered by parent component updates.

  2. Improving Performance: For functions passed to child components, if the child components are optimized using React.memo or PureComponent, useCallback ensures the stability of the function reference. This avoids unnecessary re-renders of child components.

Usage Scenarios and Examples:

Suppose we have a list component containing multiple list items, each with a 'Delete' button. When the 'Delete' button is clicked, it invokes the delete function passed down from the parent component. If we don't use useCallback to memoize this delete function, it gets re-created every time the parent component updates, causing all child list item components to re-render unnecessarily—even if they haven't changed.

jsx
import React, { useCallback, useState } from 'react'; function MyList({ items, onDeleteItem }) { return ( <ul> {items.map(item => ( <li key={item.id}> {item.name} <button onClick={() => onDeleteItem(item.id)}>Delete</button> </li> ))} </ul> ); } function App() { const [items, setItems] = useState([ { id: 1, name: 'Project 1' }, { id: 2, name: 'Project 2' }, { id: 3, name: 'Project 3' } ]); // Using `useCallback` to memoize the delete function const handleDeleteItem = useCallback((id) => { setItems(items => items.filter(item => item.id !== id)); }, []); return <MyList items={items} onDeleteItem={handleDeleteItem} />; }

In the above example, we memoize handleDeleteItem using useCallback and pass it as a prop to the MyList component. This ensures that even if the App component re-renders, the reference to handleDeleteItem remains stable, avoiding unnecessary re-renders of the MyList component.

2024年6月29日 12:07 回复

你的答案