Articles → REACT.JS → Control The Behavior Of The “Useeffects” Hooks By Passing Dependencies In React.Js

Control The Behavior Of The “Useeffects” Hooks By Passing Dependencies In React.Js






Two Ways Of Controlling The Behavior






  1. Code only executes once.
  2. Code executes when a specific UI element is rendered.



Code Only Executes Once




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


const Home = () => {

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

    useEffect(() => {
        alert("this is invoked when the content is rendered");
    }, []);

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

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


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





Code Executes When A Specific UI Element Is Rendered




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




const Home = () => {

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

    useEffect(() => {
        alert("this is invoked when the content is rendered");
    }, [country]);

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

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


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







Posted By  -  Karan Gupta
 
Posted On  -  Sunday, November 7, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250