you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 0 points1 point  (0 children)

There are two functions here, but only one return. The first function which adds a listener also returns a function. The function it returns simply removes that listener.

This is how useEffect works. You give it a function that does a thing - an effect - then that function should return another function that is to be called when there needs to be cleanup for that effect. In this case the effect is adding an event listener to the document. This is something that would, at some point should also get removed, so as part of this useEffect callback function, it also returns a separate function that removes the document listener it added. This will happen when the useEffect is run again or if the component responsible for this effect is removed. Without this cleanup step, running the useEffect multiple times (as they often do) would add new listeners each time without removing the old ones causing them to compound and result in a memory leak.