React, useEffect usage

i was going through a react course for John Smilga on freecodecamp youtube channel and he was explaining the uses of useEffect hooks. I tried to do the same example without the useEffect function and it worked exactly the same. As you can see in the following image, his original code is commented out and i just copied out “window.addEventListner(‘resize’', checkSize)” , which worked just fine.

image

so is there a difference here that am not comprehending?

Welcome there,

The difference is the component lifecycle.

Typically, you will only notice when you are working with props, and not a global state object (window). The main thing to differentiate is:

  1. When the component mounts
  2. When the component content is rendered

When the component mounts, the code before the return is run. This happens before the content is rendered.

When the content is rendered, the useEffect callback is called (only when defined to as indicated by the empty dependency array argument).

In many ways, Event Listeners acts like many of the React Lifecycle hooks do.

Hope this helps

1 Like

Thank you this really helped a lot.

Run this in the (Chrome) browser console getEventListeners(window) with and without the useEffect (obviously resize the window a few times to trigger the listener as well).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.