简体   繁体   English

如何在 React 中使用回调?

[英]How to useCallback in React?

I am curious about the difference between useEffect and useCallback .我很好奇useEffectuseCallback之间的区别。

const onUpdate = useCallback(() => {
  firebase
    .firestore()
    .collection('answer')
    .where('questionUid', '==', questionUid)
    .get()
    .then((snap) => {
      const answer = snap.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      setAnswers(answer);
    });
}, [answers]);

They are two complete different things: the aim of useEffect() is to run side effects after the component has rendered, while useCallback() aim is to memoize a callback function so that it is not re-instantiated every time the component re-renders.它们是两个完全不同的东西: useEffect()的目的是在组件渲染后运行副作用,而useCallback()的目的是记住一个回调 function,这样每次组件重新渲染时都不会重新实例化它.

useEffect() can trigger a component re-render and somehow change what the user sees in the interface, either in terms of layout (eg resizing an image in response to a viewport change) or in terms of content (eg retrieving data from an external resource) while useCallback() is a performance optimization with no evident effect for the user (well, actually in some cases forgetting to use useCallback() might lead to an infinite re-render loop but that is a different topic). useEffect()可以触发组件重新渲染并以某种方式改变用户在界面中看到的内容,无论是在布局方面(例如,调整图像大小以响应视口变化)或在内容方面(例如从外部检索数据资源),而useCallback()是一种性能优化,对用户没有明显影响(好吧,实际上在某些情况下忘记使用useCallback()可能会导致无限的重新渲染循环,但这是一个不同的主题)。

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

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