DEV Community

Santhanam Elumalai
Santhanam Elumalai

Posted on

ReactJs UseEffect Dependency (Use case)

Usecase

Consider you have a checkbox, on the toggle of the checkbox you have to get the employee information from another method if the checkbox is checked.

Solution

To begin with, I created the following things.

Assume the below method will get called once the checkbox is checked.

function getActiveEmployeeInformation(): Employee { return { name: { firstName: "Sam", lastName: "El", }, }; } 
Enter fullscreen mode Exit fullscreen mode

A Simple component to store the checkbox status and the employeeInfo.

function Employee() { const [status, updateStatus] = useState(false); const [employeeInfo, updateEmployeeInfo] = useState<Employee | null>(null); return ( <> <label> <input type="checkbox" checked={status} onChange={() => { updateStatus(!status); }} /> Is Active </label> {status && ( <p> {employeeInfo?.name.firstName} {employeeInfo?.name.lastName} </p> )} </> ); } 
Enter fullscreen mode Exit fullscreen mode

The obvious instinct will take us to write a method to be called on change of the checkbox and check the status there to call the getActiveEmployeeInformation method like below,

 function onStatusChange(){ updateStatus(!status); if(status){ const activeEmployeeInfo = getActiveEmployeeInformation(); updateEmployeeInfo(activeEmployeeInfo); } } 
Enter fullscreen mode Exit fullscreen mode

this seems like a solution, but the problem is status may not be updated right after the updateStatus call, which might lead to an inconsistent result.

To solve the above use-case, we need a simple understanding of the useEffect, in a very simple term it can be explained that when there is a change in the dependent variable the associated callback(method) will be called.

for example, if you connect, methodA to a variable employee, if any action changes the employee, that change will trigger a change-event to call the associated callback which is methodA.

Here useEffect is the connector that connects the variable and its callback.

useEffect(()=>{},[dependentVariable])

on change of the dependent variable the anonymous method will be called, using this we can solve our use case by adding the following snippet in our Employee component.

 useEffect(() => { if (status) { const activeEmployeeInfo = getActiveEmployeeInformation(); updateEmployeeInfo(activeEmployeeInfo); } }, [status]); 
Enter fullscreen mode Exit fullscreen mode

In the above snippet, we used the status as a dependent variable, on change of it the anonymous method will get the employee info if the status is true. Once I get the information I store it in a state variable for further access.

Solution

Hope you enjoyed reading this, Do let me know your feedback in the comments.

Thanks,
Sam El

Top comments (0)