乐闻世界logo
搜索文章和话题

How to add an event listener to useRef in useEffect

1个答案

1

In React, using useEffect with useRef enables adding event listeners when the component mounts and removing them when it unmounts to prevent potential memory leaks. Here is a basic example of how to add event listeners to useRef using useEffect:

javascript
import React, { useEffect, useRef } from 'react'; function MyComponent() { // Create a ref object; here we assume we are listening for a button click event const buttonRef = useRef(null); useEffect(() => { // Define the event handler const handleButtonClick = () => { console.log('Button clicked!'); }; // Access the actual DOM element via the current property const buttonElement = buttonRef.current; // Add the click event listener to the button buttonElement.addEventListener('click', handleButtonClick); // Return a cleanup function that removes the event listener when the component unmounts return () => { buttonElement.removeEventListener('click', handleButtonClick); }; // If the ref never changes, this effect can depend on an empty array and run only on mount and unmount }, []); return ( <button ref={buttonRef}>Click me</button> ); } export default MyComponent;

In this code, we use useRef to obtain a reference to the DOM element and add event listeners within the useEffect callback. Additionally, the event listeners are removed in the cleanup function returned by useEffect, which is called when the component unmounts to prevent memory leaks.

In the above code, the dependency array for useEffect is empty ([]), meaning the callback function runs only once when the component mounts and unmounts. This corresponds to the componentDidMount and componentWillUnmount lifecycle methods in class components.

Note that if the DOM element referenced by your useRef changes during the component's lifecycle, you need to handle this correctly. Typically, the DOM element pointed to by useRef should remain constant, so this scenario is rare. If you do need to handle changes, you should include the ref object or its current property as a dependency for useEffect.

2024年6月29日 12:07 回复

你的答案