简体   繁体   中英

When sould I use useCallback in React?

It's really difficult for me to decide whether to use useCallback or not. If there isn't an expensive function, should I just omit it? (But I don't know whether a function is expensive or not...)

Or when a component is re-rendered frequently, I could wrap every function in it by useCallback?

Any idea?

You can consider following use case regarding using useCallback

React's useCallback Hook can be used to optimize the rendering behavior of your React function components.

Usually useCallback is very helpful during passing callback props to child components.

Let's say if a child component that accepts a callback relies on a referential equality check to prevent unnecessary re-renders when its props change, then it is important that any callback props do not change between renders.

To do this, the parent component can wrap the callback prop in useCallback and be guaranteed that it is passing the same function object down into the optimised child component.

Let's say you have a component that renders a big list of items.

import React from 'react';
import useSearch from './fetch-items';

function ListItem({ value, handleClick }) {
  const items = useSearch(value);

  const itemToElement = item => <div onClick={handleClick}>{item}</div>;

  return <div>{items.map(itemToElement)}</div>;
}

export default React.memo(ListItem);

Here, ListItem renders a list of items. Let's imagine the list could be big, probably a few thousands of items. To preserve the list re-rendering, you wrap it into React.memo .

The parent component of ListItem needs provides a handler function when an item is clicked.

import React, { useCallback } from 'react';

export default function ParentComponent({ value }) {
  const handleClick = useCallback(item => {
    console.log('List item is clicked', item);
  }, [value]);

  return (
    <ListItem
      value={value}
      handleClick={handleClick}
    />
  );
}

handleClick callback is memoizied by useCallback() . As long as term variable stays the same, useCallback() returns the same function instance.

Even if for some reason ParentComponent component re-renders, handleClick stays the same and doesn't break the memoization of ListItem.

Notes: Please don't mix React's useCallback Hook with React's memo API. useCallback is used to memoize functions whereas React memo is used to wrap React components to prevent re-renderings. They provide two different functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM