I was working on a project and I had to close out some modals, and realized there were both Class component modals and Functional component modals that were involved... so I decided for the class component I would use the life cycle methods and use useEffect for the functional components heres what they look like
Let's get the easy stuff out of the way how are they similar..?
the handleClick function is the same barring the minor difference of using "const" in the functional component the logic of the actual function is pretty simple, if you click on the modal background or hit the esc key it should call the function that closes the modal.
Now whats the difference? its how you handle the event-listeners,
you might notice that in class components if you have an event-listener
in it, and it console.log("hello") and go to you google-developer tools
and checked console, you might notice it console logs it 3 times, this is because you haven't done what I call a clean up listener aka the removeEventListener function call so it doesn't know when to stop listening to the click, once the modal is closed there is no need for the event listener to be active! other wise it would open and close immediately when you tried to open it!
in the useEffect you do this using a "clean-up function" which you can see in the return function, this removes the event listener when the component is no longer rendered,
the equivalent to this in the class component is componentWillUnmount
inside this you can add the clean up function and now the event listener is only active while the modal is open!
pretty fun and simple function that uses some cool features!