Rules Hub
Coding Rules Library
← Back to all rules
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
frontend ruleP1universalStack: React
reacthooksevent-listenerscleanupmemory-leak
Register event listeners in useEffect and return a cleanup function
Attach global/window event listeners inside useEffect and remove them in the returned cleanup to avoid leaks and duplicate handlers.
PR: hegnar-zephr-components · org-mining-hist-2026-06Created: Jun 19, 2026
Bad example
Old codetsx
| 1 | const Comp = () => { |
| 2 | window.addEventListener('message', onMessage); // never removed |
| 3 | return <div />; |
| 4 | }; |
Explanation (EN)
Objašnjenje (HR)
Good example
New codetsx
| 1 | const Comp = () => { |
| 2 | useEffect(() => { |
| 3 | window.addEventListener('message', onMessage); |
| 4 | return () => window.removeEventListener('message', onMessage); |
| 5 | }, []); |
| 6 | return <div />; |
| 7 | }; |
Explanation (EN)
Objašnjenje (HR)