+ 1

useEffect in REACT

Can anyone explain why the event listener is used inside the useEffect, how many times useEffect will be triggered and how the returned function is working to remove the listener? Kinda feeling bamboozled. ` import React, { useState, useEffect } from "react"; // cleanup function // second argument const UseEffectCleanup = () => { const [size, setSize] = useState(window.innerWidth); // console.log(size); const checkSize = () => { setSize(window.innerWidth); }; useEffect(() => { console.log("inside useEffect"); window.addEventListener("resize", checkSize); return () => { console.log("cleaning listener"); window.removeEventListener("resize", checkSize); }; }); return ( <> <h1>Window</h1> <h2>{size} px</h2> </> ); }; export default UseEffectCleanup; `

2nd Sep 2021, 4:42 AM
NBinte
NBinte - avatar
2 Respostas
+ 2
Hey there, I myself am just learning React, but I'll try and explain it in very simple terms, hope it might help you . Basically, the listener is in the useEffect hook, because this way the listener will only be triggered ONCE and that is when the component is FIRST rendered to the screen, and not everytime the component changes or alters: useEffect(() => { console.log("inside useEffect"); window.addEventListener("resize", checkSize); return () => { console.log("cleaning listener"); window.removeEventListener("resize", checkSize); }; },[] ); /****SEE this empty bracket at end of the UseEffect? That tells it to only run when the component is first rendered, and not everytime the component may change ***/ I might have sucked at explaining it lol so heres a page that helped me understand it a bit more, hope it helps you too and I hope I did a little bit: https://www.pluralsight.com/guides/event-listeners-in-react-components
5th Sep 2021, 8:04 AM
Izac Espinoza
Izac Espinoza - avatar
0
Izac Espinoza thanks :)
6th Sep 2021, 3:13 AM
NBinte
NBinte - avatar