Articles → REACT.JS → Clean up function of the useEffect hooks in react.js

Clean up function of the useEffect hooks in react.js






Purpose





Syntax


useEffect(() => {
  // This is the effect itself.
  return () => {
    // This is its cleanup.
  };
});



Example


import React, { useState, useEffect  } from 'react';
import ReactDOM from 'react-dom';




const Home = () => {

    const [name, setName] = useState('Gyan');

    useEffect(() => {
        console.log("this is invoked when the content is rendered");

        return () => {
            console.log("useeffect return");
        };

    });

    const handleNameClick = () => {
        setName('Gyansangrah');
    }

    return (
        <div>
            <p>{name}</p>
            <button onClick={handleNameClick}>Set Name</button>
        </div>
    );
}


ReactDOM.render(<Home />, document.getElementById('root'));



Output


Picture showing the output of Clean up function of the useEffect hooks in react.js

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Monday, November 15, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250