React why should I remove event listeners?











up vote
8
down vote

favorite












I see a lot of code like this:



componentDidMount() {
// add event listener
}

componentWillUnmount() {
// remove event listener
}


I understand if the listener is set on something global like window, but if it's just on an HTML element within the component that's about to be unmounted, won't the listener disappear with the component anyway?










share|improve this question




























    up vote
    8
    down vote

    favorite












    I see a lot of code like this:



    componentDidMount() {
    // add event listener
    }

    componentWillUnmount() {
    // remove event listener
    }


    I understand if the listener is set on something global like window, but if it's just on an HTML element within the component that's about to be unmounted, won't the listener disappear with the component anyway?










    share|improve this question


























      up vote
      8
      down vote

      favorite









      up vote
      8
      down vote

      favorite











      I see a lot of code like this:



      componentDidMount() {
      // add event listener
      }

      componentWillUnmount() {
      // remove event listener
      }


      I understand if the listener is set on something global like window, but if it's just on an HTML element within the component that's about to be unmounted, won't the listener disappear with the component anyway?










      share|improve this question















      I see a lot of code like this:



      componentDidMount() {
      // add event listener
      }

      componentWillUnmount() {
      // remove event listener
      }


      I understand if the listener is set on something global like window, but if it's just on an HTML element within the component that's about to be unmounted, won't the listener disappear with the component anyway?







      javascript reactjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 at 9:21









      Samuel J Mathew

      3,41412228




      3,41412228










      asked Nov 12 at 6:07









      Mirror318

      4,90422941




      4,90422941
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          8
          down vote



          accepted










          The event listeners need to be removed due to following reason.




          • Avoid memory leaks, if the browser is not handled it properly.Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

          • Avoid collisions of events of components.

          • Remove the side effects when the reference of event listeners are stored in some persistence such as local storage or some thing like this


          Here is a good article to get an insights on event listners






          share|improve this answer






























            up vote
            5
            down vote













            Modern browsers do remove event listeners on components when they are unmounted, however for some reason if you store the reference of this node in any other component that is not mounted or in localStorage, Garbage collector will not be able process this and it can potentially cause memory leaks.



            Hence, the safest way to handle such scenarios is to manually remove event listeners in componentWillUnmount.



            P.S. With hooks, react provides way to return a function which can be used to remove listeners in the useEffect hook.






            share|improve this answer




























              up vote
              1
              down vote













              If event listeners are not removed, it will cause memory leak for older browsers (IE 6 and 7, if i recall correctly). Hence will cause unnecessarily high memory utilization which will lead to many problems. Also, in this case, you will have issues with debugging as in a big project you never have control of the entire codebase and you can have multiple references of same component loaded from different components and if memory leak is not handled by the browser, then it will create a lot of confusion regarding the triggered events.






              share|improve this answer





















                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256662%2freact-why-should-i-remove-event-listeners%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                8
                down vote



                accepted










                The event listeners need to be removed due to following reason.




                • Avoid memory leaks, if the browser is not handled it properly.Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

                • Avoid collisions of events of components.

                • Remove the side effects when the reference of event listeners are stored in some persistence such as local storage or some thing like this


                Here is a good article to get an insights on event listners






                share|improve this answer



























                  up vote
                  8
                  down vote



                  accepted










                  The event listeners need to be removed due to following reason.




                  • Avoid memory leaks, if the browser is not handled it properly.Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

                  • Avoid collisions of events of components.

                  • Remove the side effects when the reference of event listeners are stored in some persistence such as local storage or some thing like this


                  Here is a good article to get an insights on event listners






                  share|improve this answer

























                    up vote
                    8
                    down vote



                    accepted







                    up vote
                    8
                    down vote



                    accepted






                    The event listeners need to be removed due to following reason.




                    • Avoid memory leaks, if the browser is not handled it properly.Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

                    • Avoid collisions of events of components.

                    • Remove the side effects when the reference of event listeners are stored in some persistence such as local storage or some thing like this


                    Here is a good article to get an insights on event listners






                    share|improve this answer














                    The event listeners need to be removed due to following reason.




                    • Avoid memory leaks, if the browser is not handled it properly.Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

                    • Avoid collisions of events of components.

                    • Remove the side effects when the reference of event listeners are stored in some persistence such as local storage or some thing like this


                    Here is a good article to get an insights on event listners







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 12 at 9:25

























                    answered Nov 12 at 6:15









                    Samuel J Mathew

                    3,41412228




                    3,41412228
























                        up vote
                        5
                        down vote













                        Modern browsers do remove event listeners on components when they are unmounted, however for some reason if you store the reference of this node in any other component that is not mounted or in localStorage, Garbage collector will not be able process this and it can potentially cause memory leaks.



                        Hence, the safest way to handle such scenarios is to manually remove event listeners in componentWillUnmount.



                        P.S. With hooks, react provides way to return a function which can be used to remove listeners in the useEffect hook.






                        share|improve this answer

























                          up vote
                          5
                          down vote













                          Modern browsers do remove event listeners on components when they are unmounted, however for some reason if you store the reference of this node in any other component that is not mounted or in localStorage, Garbage collector will not be able process this and it can potentially cause memory leaks.



                          Hence, the safest way to handle such scenarios is to manually remove event listeners in componentWillUnmount.



                          P.S. With hooks, react provides way to return a function which can be used to remove listeners in the useEffect hook.






                          share|improve this answer























                            up vote
                            5
                            down vote










                            up vote
                            5
                            down vote









                            Modern browsers do remove event listeners on components when they are unmounted, however for some reason if you store the reference of this node in any other component that is not mounted or in localStorage, Garbage collector will not be able process this and it can potentially cause memory leaks.



                            Hence, the safest way to handle such scenarios is to manually remove event listeners in componentWillUnmount.



                            P.S. With hooks, react provides way to return a function which can be used to remove listeners in the useEffect hook.






                            share|improve this answer












                            Modern browsers do remove event listeners on components when they are unmounted, however for some reason if you store the reference of this node in any other component that is not mounted or in localStorage, Garbage collector will not be able process this and it can potentially cause memory leaks.



                            Hence, the safest way to handle such scenarios is to manually remove event listeners in componentWillUnmount.



                            P.S. With hooks, react provides way to return a function which can be used to remove listeners in the useEffect hook.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 12 at 6:24









                            Shubham Khatri

                            77k1490126




                            77k1490126






















                                up vote
                                1
                                down vote













                                If event listeners are not removed, it will cause memory leak for older browsers (IE 6 and 7, if i recall correctly). Hence will cause unnecessarily high memory utilization which will lead to many problems. Also, in this case, you will have issues with debugging as in a big project you never have control of the entire codebase and you can have multiple references of same component loaded from different components and if memory leak is not handled by the browser, then it will create a lot of confusion regarding the triggered events.






                                share|improve this answer

























                                  up vote
                                  1
                                  down vote













                                  If event listeners are not removed, it will cause memory leak for older browsers (IE 6 and 7, if i recall correctly). Hence will cause unnecessarily high memory utilization which will lead to many problems. Also, in this case, you will have issues with debugging as in a big project you never have control of the entire codebase and you can have multiple references of same component loaded from different components and if memory leak is not handled by the browser, then it will create a lot of confusion regarding the triggered events.






                                  share|improve this answer























                                    up vote
                                    1
                                    down vote










                                    up vote
                                    1
                                    down vote









                                    If event listeners are not removed, it will cause memory leak for older browsers (IE 6 and 7, if i recall correctly). Hence will cause unnecessarily high memory utilization which will lead to many problems. Also, in this case, you will have issues with debugging as in a big project you never have control of the entire codebase and you can have multiple references of same component loaded from different components and if memory leak is not handled by the browser, then it will create a lot of confusion regarding the triggered events.






                                    share|improve this answer












                                    If event listeners are not removed, it will cause memory leak for older browsers (IE 6 and 7, if i recall correctly). Hence will cause unnecessarily high memory utilization which will lead to many problems. Also, in this case, you will have issues with debugging as in a big project you never have control of the entire codebase and you can have multiple references of same component loaded from different components and if memory leak is not handled by the browser, then it will create a lot of confusion regarding the triggered events.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 12 at 6:31









                                    Arnab

                                    312




                                    312






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256662%2freact-why-should-i-remove-event-listeners%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Bressuire

                                        Vorschmack

                                        Quarantine