简体   繁体   English

何时使用 React useCallback 钩子

[英]When to use React useCallback hook

In my below React component I am fetching more items using Apollo Client fetchMore function .在下面的 React 组件中,我使用Apollo Client fetchMore function获取更多项目。

What is exactly the purpose of using React useCallback hook here?在这里使用React useCallback 钩子的目的究竟是什么? And is it good idea to use that in this case?在这种情况下使用它是个好主意吗?

const Carousel = ({ data: blockData, metadata }: Props) => {

  const { data, fetchMore, networkStatus } = useQuery<
   GqlRes,
  >(GET_NODES, {
    variables: {
      offset
      limit
    },
    errorPolicy: 'all',
    notifyOnNetworkStatusChange: true,
    ssr: false,
  });


  const fetchNextPage = useCallback(() => {
    return fetchMore({
      variables: {
        offset: data?.getNodes.nodes.length,
      },
    });
  }, [data, fetchMore]);

  const items =
    data?.getNodes.nodes
      .map((node) => {
        return {
          id: node.id,
          title: node.title,
        };
      }) || [];

  return (
    <Carousel
      items={items}
        onEnd={() => {
         if (data?.getNodes.pager?.hasNextPage) {
           fetchNextPage();
         }
      }}
    />
  )
};

export default Carousel;

IMHO:恕我直言:

  1. if your inner 'Carousel' component is cached (memoized by React.memo or extends PureComponent ) it's could to do not provide new properties on each parent (outer 'Carousel') re-render (just to mention - on each re-render you not memoized objects and function will be created again as new instances and will be passed further as new properties and cause new re-renders of children) it's to use useCallback如果您的内部“轮播”组件被缓存(由React.memo或扩展PureComponent ),则可以不在每个父级(外部“轮播”)上提供新属性重新渲染(仅提一下 - 每次重新渲染你没有记忆的对象和 function 将作为新实例再次创建,并将作为新属性进一步传递并导致新的子级重新渲染)使用useCallback
  2. even more, I would like to use useMemo for your ' items ' data variable to avoid that logic re-handling.更重要的是,我想将useMemo用于您的“项目”数据变量,以避免重新处理逻辑。 Yes for it's logically will be new on each update of ' data ' or other properties from a parent, BUT when someone will extend the logic of the component and it will be re-rendered, then data handling could be not changed and that logic will be redundant - you safe time of component logic handling是的,因为从逻辑上讲,每次更新“数据”或父级的其他属性时,它都是新的,但是当有人扩展组件的逻辑并将重新渲染时,数据处理可能不会改变,并且该逻辑将是多余的 - 你的组件逻辑处理的安全时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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