[英]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:恕我直言:
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
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.