
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Cleaning Up with useEffect Hook in ReactJS
In this article, we are going to see how to clean up the subscriptions set up in the useEffect hook in the functional component.
Once the effects are created, then they are needed to be cleaned up before the component gets removed from the DOM. For this, cleaning up effect is used to remove the previous useEffect hook’s effect before using this hook of the same component again.
Syntax
useEffect(()=>{ return ()=>{} } ,[]);
Example
In this example, we will build a React application which displays the coordinates of the mouse pointer when it is moved over the screen. For this to implement, we will write the code with both cleanup effects and without it.
Without Clean Up Effect
Example
App.jsx
import React, { useEffect, useState } from 'react'; function App() { return ( <div className="App"> <Comp /> </div> ); } function Comp() { useEffect(() => { document.addEventListener('mousemove', mouseHandler); }, []); const mouseHandler = (e) => { console.log(e.clientX, e.clientY); }; return ( <div> <h1>Tutorialspoint</h1> </div> ); } export default App;
In the above example, we are not removing the previous useEffect hook’s data, which is affecting the new data returned by this hook.
Output
This will produce the following result.
With Clean Up Effect
Example
App.jsx
import React, { useEffect, useState } from 'react'; function App() { return ( <div className="App"> <Comp /> </div> ); } function Comp() { useEffect(() => { document.addEventListener('mousemove', mouseHandler); return () => { document.removeEventListener('mousemove', mouseHandler); }; }, []); const mouseHandler = (e) => { console.log(e.clientX, e.clientY); }; return ( <div> <h1>Tutorialspoint</h1> </div> ); } export default App;
In the above example, useEffect hook is called with the cleanup effect and thus, the effect of this hook will get removed every time the component gets destroyed.
Output
This will produce the following result.