What’s the difference between using one or two Arrow Functions in Useeffect?

Asked

Viewed 37 times

3

In this reply from Soen, one uses a useEffect with two Arrow functions followed. Thus:

useEffect(() => () => {
  window.removeEventListener('resize', compareSize);
}, []);

I wonder why the duo Arrow Function is being used up there. What is the difference between a useEffect with only one Arrow Function for a useEffect with two Arrow functions (as the above example)?

For example, this:

useEffect(() => {
  compareSize();
  window.addEventListener('resize', compareSize);
}, []);

1 answer

2


It is known that functions returned by the function passed to the useEffect are used by React as the Cleanup Effect, that is, it will be executed when the component is disassembled.

Therefore, do:

// Este `useEffect` só executa código em cleanup
useEffect(() => () => {
  window.removeEventListener('resize', compareSize);
});

It’s the same as this:

// Este `useEffect` só executa código em cleanup
useEffect(() => {
  return () => {
    window.removeEventListener('resize', compareSize);
  };
});

Dessarte, both of you useEffectQuestion s can be "merged" into one, so:

useEffect(() => {
  compareSize();
  window.addEventListener('resize', compareSize);
  
  // Efeito de cleanup:
  return () => {
    window.removeEventListener('resize', compareSize);
  };
}, []);

To better understand the syntax, see what they are Arrow functions. On the effects of Cleanup and useEffect in general, refer to the react documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.