Using the useEffect hook in React to add and clean up event listeners is a common pattern. Adding listeners is typically implemented within the callback function of useEffect, while removing listeners is handled in the cleanup function. Let's illustrate this with a concrete example.
Suppose we have a component that needs to perform certain actions when the user clicks on the page. We'll use useEffect to add and remove this click event listener.
javascriptimport React, { useEffect } from 'react'; function ClickHandlerComponent() { useEffect(() => { // Define the event handler function const handleDocumentClick = () => { console.log('The page was clicked!'); }; // Add the event listener document.addEventListener('click', handleDocumentClick); // Return a cleanup function // When the component unmounts, React automatically executes this function to clean up resources return () => { // Remove the event listener document.removeEventListener('click', handleDocumentClick); }; }, []); // Empty dependency array indicates this effect runs only once on mount and cleans up on unmount return <div>Click on the page to see console output.</div>; } export default ClickHandlerComponent;
In this example:
- Within the callback function of
useEffect, we add an event listener for the globalclickevent. - We define the
handleDocumentClickfunction, which is invoked whenever a click event occurs. - Using
addEventListener, we registerhandleDocumentClickas the listener for theclickevent. - The
useEffecthook returns a cleanup function that contains the logic to remove the corresponding event listener usingremoveEventListener. - When the component unmounts, React automatically calls this cleanup function to perform cleanup operations, preventing memory leaks.
This is a typical example of adding and cleaning up event listeners within useEffect. Using this pattern ensures that component resources are properly managed and prevents leaving uncleaned event listeners after the component unmounts.
2024年6月29日 12:07 回复