1

I am curious about the difference between useEffect and useCallback.

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]);
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • 2
    I had the same doubt today morning and read this article...this explains quite clearly. https://medium.com/@infinitypaul/reactjs-useeffect-usecallback-simplified-91e69fb0e7a3. Hope this helps – Prabhu Dec 16 '20 at 14:53
  • Does this answer your question? [When to use useCallback, useMemo and useEffect?](https://stackoverflow.com/questions/56910036/when-to-use-usecallback-usememo-and-useeffect) – Mohammad Hossein Amri Dec 16 '20 at 15:03

1 Answers1

0

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() can trigger a component re-render and somehow change what the user sees in the interface, either in terms of layout (e.g. resizing an image in response to a viewport change) or in terms of content (e.g. 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).

secan
  • 2,622
  • 1
  • 7
  • 24