useEffect Part-3
When we develop one application, we develop multiple components as part of it. User will be navigating from one component to another component. Just like going from Employees Tab to Departments and then navigating to Projects tabs.
When we go from one Component to the Other Component, the Previous component will be removed from the DOM and the new Component contents will be displayed in the UI.
This is called Unmounting.
When that happens, we have to Perform any necessary cleanup required, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in that respective component.
We have discussed about similar example in the Case of Class Components. Class Components have one life cycle method called as componentWillUnmount and we write such clean up code inside that method.
Lets understand how do we do that in the Case of function components.
Lets create our Employee Component,
Lets create one state variable named as employeeCount and pass a function to update the same. We will initialize it to 0.
Lets add effect hook, and with in that we will write the code to get the list of employees from our Web API. I have the code handy and pasting it here. With in the getEmployees function, when we get the response we will update our employeeCount value.
We will call that function from our effect.
Lets return one div container. With in this div we will display the employee count.
Now we wanted our getEmployees function to be called for every 5 seconds and show us the updated count. As we have done in our previous video, we will call that getEmployees function using setInterval function and we will give 5 seconds as the interval.
Lets add one alert within our getEmployeesCount function so that we will be notified when that method is called.
Lets create another component called as Departments component and we will return a simple message from this component.
Now we will place a button in the Employee Component and on click of that button, we will render Department Component.
Lets call our Employee Component and render that to our root container.
Save the changes, navigate to the browser. We can see the output.
We can observe that we will get the alert for every five seconds.
Lets Click on the Departments Button. We will see the contents of Departments Component. But one can observe that we will get the Employee Components alert notifications even when we are inside Department Component. Ideally that should not happen.
We have clear the interval which is being set so that we don’t introduce a memory leak.
When we want to do any clean up tasks, we dont need a separate effect to perform the cleanup.
We can do that in the same effect. Lets see how do we do that.
Any Clean up code we wanted to be executed when the Component is Unmounted, we will write it in a function and we will return that function from our effect.
React calls that function when the component unmounts. The function can be a named function or an arrow function as well.
As we have discussed in our Previous articles, we will use clearInterval method of javasript to clear that Interval. But to that clearInterval method, we have to pass the handle. We know that when we call setInterval method, it returns a handle. We will pass that handle to our clearInterval. Save the changes, navigate to the browser.
We can observe that we will get the alert for every five seconds.
Lets Click on the Departments Button. We will see the contents of Departments Component. But one can observe that we dont get the Employee Components alert notifications when we are inside Department Component that is because the cleanUp is done.
As we have seen the useEffect Hook is the combination of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods.
Currently we are display the number of Employees in our Employee Component. Lets say we have to display another message which shows when did the last employee added. Like Last Employee is added one day ago, two days ago something like that.
Lets create another state variable noOfDaysCount. We have to get this value also from our WebAPI. Assuming that we have TestApi which gives the noOfDays value.
With in our effect, lets write the code to call the Web API and assign it to our noOfDays state variable.
If we observe the our effect hook code, we are dumping everything in one place. Instead of that, like how we use the State Hook more than once, we can also use several effects. This lets us separate unrelated logic into different effects.
React will apply every effect used by the component, in the order they were specified.
I am sure by this time, we are very clear on what is effect hook, how to use that in our React Projects.
import ReactDOM from "react-dom";
import React, { Component, useState, useEffect } from "react";
function Employee(){
const [employeeCount, setEmployeeCount]=useState(0);
const [noOfDays,setNoOfDays]=useState(0);
useEffect(()=>{
var handle=setInterval(getEmployeesCount,5000);
return ()=>{
clearInterval(handle);
}
});
useEffect(()=>{
fetch("https://localhost:44306/api/Test")
.then(res => res.json())
.then(
(result) => {
setNoOfDays(result);
}
);
})
function getEmployeesCount(){
alert('Getting the Employees Count');
fetch("https://localhost:44306/api/Employee")
.then(res => res.json())
.then(
(result) => {
setEmployeeCount(result.length);
}
);
}
function navigateToDepartment(){
ReactDOM.render(<Departments></Departments>,document.getElementById("root"));
}
return (
<div>
<h2>Welcome to Employee Component...</h2>
<p>
<label>Employee Count : <b>{employeeCount}</b></label>
</p>
<p>
<label>Last Employee Added : <b>{noOfDays} days ago...</b></label>
</p>
<button onClick={navigateToDepartment}>Departments</button>
</div>
)
}
function Departments(){
return(
<div>
<h2>Welcome to Departments Component...</h2>
</div>
)
}
const element=<Employee></Employee>
ReactDOM.render(element,document.getElementById("root"));
Video Reference:
© 2020 Pragimtech. All Rights Reserved.