useCallback
时间: 2023-10-13 11:00:06 浏览: 33
`useCallback` is a hook in React that is used to memoize a function. It is useful when you want to optimize the performance of your components by preventing unnecessary re-renders caused by passing new references of functions as props to child components.
When you wrap a function with `useCallback`, React will memoize the function and only create a new instance when one of the dependencies provided in the dependency array changes. This means that the memoized function will be the same between renders unless its dependencies have changed, allowing you to optimize performance.
Here's an example of how to use `useCallback`:
```jsx
import React, { useCallback } from 'react';
const MyComponent = () => {
const handleClick = useCallback(() => {
console.log('Button clicked!');
}, []);
return (
<button onClick={handleClick}>Click Me</button>
);
};
```
In the example above, `handleClick` will only be created once during the initial render of `MyComponent` because it has an empty dependency array (`[]`). If there were any dependencies in the array, `handleClick` would be recreated whenever one of those dependencies changes.
Using `useCallback` can help optimize the performance of your React components by preventing unnecessary re-renders when passing functions as props.