How to remove event listeners in React
To remove an event listener in React:
-
useEffect
Add event listeners in the hook . -
useEffect
Return a function from the hook. -
When the component unmounts,
removeEventListener
remove the event listener using the method.
import {useRef, useEffect} from 'react';
const App = () => {
const ref = useRef(null);
useEffect(() => {
const handleClick = event => {
console.log('Button clicked');
};
const element = ref.current;
element.addEventListener('click', handleClick);
// 👇️ remove the event listener when the component unmounts
return () => {
element.removeEventListener('click', handleClick);
};
}, []);
return (
<div>
<button ref={ref}>Click</button>
</div>
);
};
export default App;
useEffect
We added an event listener to an element in the component's hook.
If you want to add an event listener to the window or document object, use the same method but without the
ref
.
useEffect(() => {
const handleClick = event => {
console.log('Button clicked');
};
const element = ref.current;
element.addEventListener('click', handleClick);
// 👇️ remove the event listener when the component unmounts
return () => {
element.removeEventListener('click', handleClick);
};
}, []);
We pass an empty dependencies
array to useEffect
the hook, so it will only run when the component mounts.
We only want to call addEventListener
the method once - when the component mounts.
We store a reference to the element in a variable and use
addEventListener
the method to add a click event listener to the button.
The method takes as its first argument the type of event to listen for, and as its second argument a function to be called when an event of the specified type occurs.
The function we return from the useEffect hook is called when the component unmounts.
return () => {
element.removeEventListener('click', handleClick);
};
We use removeEventListener
the method to remove the event listener we registered previously.
The cleanup step is important because we want to make sure that we don't have any memory leaks in our application.
removeEventListener
The 2 parameters we pass to the method are:
- The event type to remove the event listener for.
- The corresponding event handling function.
Here's a better way to visualize how to remove event listeners in React.
import {useRef, useState, useEffect} from 'react';
const Box = () => {
const ref = useRef(null);
useEffect(() => {
const handleClick = event => {
console.log('Button clicked');
console.log('jiyik.com');
};
const element = ref.current;
element.addEventListener('click', handleClick);
// 👇️ remove the event listener when the component unmounts
return () => {
element.removeEventListener('click', handleClick);
console.log('✅ Event listener removed');
};
}, []);
return (
<div>
<button ref={ref}>Click</button>
</div>
);
};
const App = () => {
const [isShown, setIsShown] = useState(true);
return (
<div>
{isShown && <Box />}
<br />
<br />
<button onClick={() => setIsShown(isShown => !isShown)}>
Toggle box visibility
</button>
</div>
);
};
export default App;
The Box component registers a click event listener that is triggered every time the user clicks the button.
The component's useEffect
cleanup hook returns a cleanup function that is run when the component is unmounted.
return () => {
element.removeEventListener('click', handleClick);
console.log('✅ Event listener removed');
};
We used a boolean state variable in the App component to render and unmount the Box component.
When the Box component unmounts, an "Event listener removed" message will be logged to the console and the event listener will be removed.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Using onChange event in React
Publish Date:2025/03/03 Views:148 Category:React
-
onChange 是 React 中最常见的输入事件之一。本文将帮助你了解它的工作原理。
Checkbox onChange in React
Publish Date:2025/03/03 Views:73 Category:React
-
本教程演示了如何从 React 中 onChange 事件的复选框发送值。
onDoubleClick in React
Publish Date:2025/03/03 Views:128 Category:React
-
本教程演示了如何在 React 中使用 onDoubleClick。
Show element or text on hover in React
Publish Date:2025/03/03 Views:186 Category:React
-
在 React 中悬停时显示元素或文本: 在元素上设置 onMouseOver 和 onMouseOut 属性。 跟踪用户是否将鼠标悬停在状态变量中的元素上。 根据状态变量有条件地渲染另一个元素。 import {useStat
Scroll to top of page in React.js
Publish Date:2025/03/03 Views:182 Category:React
-
在 React 中使用 window.scrollTo() 方法滚动到页面顶部,例如 window.scrollTo(0, 0) 。 window 对象上的 scrollTo 方法滚动到文档中的一组特定坐标。 import {useEffect} from react ; export default function App (
Applying global CSS styles in React applications
Publish Date:2025/03/03 Views:145 Category:React
-
要在 React 应用程序中应用全局 CSS 样式,请将 CSS 写入扩展名为 .css 的文件中,并将其导入 index.js 文件中。 全局 CSS 应该在 index.js 中导入,以确保它被加载到你的 React 应用程序的所有
Passing events and parameters to onClick in React
Publish Date:2025/03/03 Views:63 Category:React
-
在 React 中传递事件和参数 onClick: 将内联函数传递给元素的 onClick 属性。 该函数应获取事件对象并调用 handleClick 。 将事件和参数传递给 handleClick 。 const App = () = { const handleClick = ( e
Using conditions to jump out of a map in map() in React
Publish Date:2025/03/03 Views:147 Category:React
-
Using conditions in map() in React: Call the map() method on an array. Use an if condition to explicitly return if the condition is met. Otherwise return a different value or return null to render nothing. export default function App () { const arr =
Calling multiple onClick functions in React
Publish Date:2025/03/03 Views:105 Category:React
-
To call multiple onClick functions in React: Set the onClick attribute on the element. Call other functions in the event handler. The event handler can call as many other functions as needed. export default function App () { const s