Rules Hub
Coding Rules Library
Prefer AbortController for event listener cleanup
Use AbortController to manage event listener lifecycle instead of manually pairing addEventListener and removeEventListener.
Bad example
| 1 | useEffect(() => { |
| 2 | const handleResize = () => { |
| 3 | console.log('Window resized'); |
| 4 | }; |
| 5 |
|
| 6 | window.addEventListener('resize', handleResize); |
| 7 |
|
| 8 | return () => { |
| 9 | // Relies on keeping the exact function reference stable |
| 10 | window.removeEventListener('resize', handleResize); |
| 11 | }; |
| 12 | }, []); |
Explanation (EN)
Using removeEventListener requires passing the exact same function reference used in addEventListener. If the handler is anonymous or wrapped, the cleanup fails silently. It also requires repeating the event name and options.
Objašnjenje (HR)
Korištenje removeEventListener zahtijeva prosljeđivanje točno iste reference funkcije korištene u addEventListener. Ako je handler anoniman ili omotan, čišćenje neće uspjeti bez greške. Također zahtijeva ponavljanje naziva događaja i opcija.
Good example
| 1 | useEffect(() => { |
| 2 | const controller = new AbortController(); |
| 3 |
|
| 4 | window.addEventListener( |
| 5 | 'resize', |
| 6 | () => console.log('Window resized'), |
| 7 | { signal: controller.signal } |
| 8 | ); |
| 9 |
|
| 10 | return () => { |
| 11 | // Cleanly removes all listeners attached to this signal |
| 12 | controller.abort(); |
| 13 | }; |
| 14 | }, []); |
Explanation (EN)
Passing a signal to addEventListener allows you to remove the listener simply by calling controller.abort(). This eliminates the need to maintain stable function references and makes the cleanup logic concise and robust.
Objašnjenje (HR)
Prosljeđivanje signala u addEventListener omogućuje uklanjanje slušatelja jednostavnim pozivom controller.abort(). To uklanja potrebu za održavanjem stabilnih referenci funkcija i čini logiku čišćenja sažetom i robusnom.
Notes (EN)
This pattern is supported in all modern browsers. It is especially useful in React useEffect hooks to avoid stale closures or complex dependency management for event handlers.
Bilješke (HR)
Ovaj obrazac podržan je u svim modernim preglednicima. Posebno je koristan u React useEffect hookovima kako bi se izbjegli 'stale closures' ili složeno upravljanje ovisnostima za handlere događaja.