<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Olatunde Adedeji</title>
    <description>The latest articles on DEV Community by Olatunde Adedeji (@olatundeadedeji).</description>
    <link>https://dev.to/olatundeadedeji</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F814798%2F2a14a54e-0545-43b2-841e-43df5fe4bd0e.jpeg</url>
      <title>DEV Community: Olatunde Adedeji</title>
      <link>https://dev.to/olatundeadedeji</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/olatundeadedeji"/>
    <language>en</language>
    <item>
      <title>Mastering SOLID Principles in Python: A Guide to Scalable Coding</title>
      <dc:creator>Olatunde Adedeji</dc:creator>
      <pubDate>Tue, 04 Jul 2023 18:17:43 +0000</pubDate>
      <link>https://dev.to/olatundeadedeji/mastering-solid-principles-in-python-a-guide-to-scalable-coding-bbn</link>
      <guid>https://dev.to/olatundeadedeji/mastering-solid-principles-in-python-a-guide-to-scalable-coding-bbn</guid>
      <description>&lt;p&gt;SOLID principles are a set of software design principles that aim to help software developers write scalable and maintainable codes. These standard principles for software design are the &lt;code&gt;Single responsibility principle&lt;/code&gt;, &lt;code&gt;Open-closed principle&lt;/code&gt;, &lt;code&gt;Liskov substitution principle&lt;/code&gt;, &lt;code&gt;Interface segregation principle&lt;/code&gt;, and &lt;code&gt;Dependency inversion principle&lt;/code&gt;. Before the SOLID principles adoption, software developers faced several challenges related to writing codes that are easier to maintain and understand. Tech folks that design with codes faced issues related to code becoming tangled and difficult to understand, which was sometimes referred to as &lt;code&gt;spaghetti code&lt;/code&gt;. This made it difficult to make changes or add new features to the codebase and could result in bugs and other unintended issues.&lt;/p&gt;

&lt;p&gt;Another prevailing problem precedent to SOLID was code rigidity, where making changes to one part of the codebase would require changes to many other parts of the codebase. This made it difficult to make changes to the codebase without introducing bugs or breaking existing functionality. We also experienced a lack of modularity, where code was not divided into smaller, more manageable components. This made it difficult to reuse code and made the codebase more difficult to understand and maintain.&lt;/p&gt;

&lt;p&gt;SOLID principles were introduced by Robert C. Martin, also known as Uncle Bob, in the early 2000s to address these and other challenges by providing a set of best practices for writing maintainable and scalable code. With the SOLID creed, software developers can create code that is easier to understand, easier to maintain, and more flexible in the face of changing requirements.&lt;br&gt;
Next, we discuss the components of SOLID principles.&lt;/p&gt;
&lt;h2&gt;
  
  
  What are SOLID Design Principles
&lt;/h2&gt;

&lt;p&gt;SOLID principles are software design best practices formulated to help software developers write maintainable, scalable, and flexible code.&lt;/p&gt;

&lt;p&gt;Let's delve deeper into understanding SOLID principles with some Python code examples to drive SOLID creed into our blood streams:&lt;/p&gt;

&lt;p&gt;The five SOLID principles are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Single Responsibility Principle (SRP): A class should have a single responsibility or a single job&lt;/li&gt;
&lt;li&gt;Open/Closed Principle (OCP): A class should be open for extension but closed for modification.&lt;/li&gt;
&lt;li&gt;Liskov Substitution Principle (LSP): derived classes should be substitutable for their base classes.&lt;/li&gt;
&lt;li&gt;Interface Segregation Principle (ISP): Clients/classes that use an interface should not be forced to depend on interfaces they do not use.&lt;/li&gt;
&lt;li&gt;Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules; both should depend on abstractions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Next, we will slice each principle and sprinkle some Python codes on these best practices to help us understand the SOLID principles better.&lt;/p&gt;
&lt;h2&gt;
  
  
  Single Responsibility Principle
&lt;/h2&gt;

&lt;p&gt;The Single Responsibility Principle (SRP) is a fundamental SOLID principle that states that a class should have single responsibility or a single job. This principle helps in making the code more maintainable, testable, and reusable.&lt;/p&gt;

&lt;p&gt;Let's buttress the point with a healthcare application.&lt;/p&gt;

&lt;p&gt;To demonstrate the single responsibility principle using a sample Python code, let's consider a case study of a healthcare application. Suppose we have a class called Patient that has the following properties: &lt;code&gt;name&lt;/code&gt;, age, &lt;code&gt;gender&lt;/code&gt;, &lt;code&gt;blood_group&lt;/code&gt;, &lt;code&gt;patient_id&lt;/code&gt;, &lt;code&gt;medical_history&lt;/code&gt;, &lt;code&gt;appointments&lt;/code&gt;, and &lt;code&gt;treatments&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;However, the &lt;code&gt;Patient&lt;/code&gt; class violates the SRP principle because it has too many responsibilities. It stores patient &lt;code&gt;data&lt;/code&gt;, &lt;code&gt;medical history&lt;/code&gt;, &lt;code&gt;appointments&lt;/code&gt;, and &lt;code&gt;treatments&lt;/code&gt; all in one class. A better approach would be to separate the concerns of patient data storage and appointment scheduling into two separate classes.&lt;/p&gt;

&lt;p&gt;A code example is provided below to illustrate this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Patient:
    def __init__(self, name, age, gender, blood_group, patient_id, medical_history, appointments, treatments):
        self.name = name
        self.age = age
        self.gender = gender
        self.blood_group = blood_group
        self.patient_id = patient_id
        self.medical_history = medical_history
        self.appointments = appointments
        self.treatments = treatments

    def get_patient_data(self):
        # return patient data

    def get_medical_history(self):
        # return medical history

    def get_appointments(self):
        # return appointments

    def get_treatments(self):
        # return treatments

    def schedule_appointment(self, date):
        # schedule an appointment

    def add_treatment(self, treatment):
        # add a new treatment
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The preceding &lt;code&gt;Patient&lt;/code&gt; class violates the SRP principle because it has too many responsibilities. We can refactor the code and separate concerns by creating a &lt;code&gt;PatientData&lt;/code&gt; class and an &lt;code&gt;AppointmentScheduler&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PatientData:
    def __init__(self, name, age, gender, blood_group, patient_id, medical_history, treatments):
        self.name = name
        self.age = age
        self.gender = gender
        self.blood_group = blood_group
        self.patient_id = patient_id
        self.medical_history = medical_history
        self.treatments = treatments

    def get_patient_data(self):
        # return patient data

    def get_medical_history(self):
        # return medical history

    def get_treatments(self):
        # return treatments


class AppointmentScheduler:
    def __init__(self, patient_data):
        self.patient_data = patient_data
        self.appointments = []

    def get_appointments(self):
        # return appointments

    def schedule_appointment(self, date):
        # schedule an appointment
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the preceding refactored code, we have separated concerns and created two classes. The &lt;code&gt;PatientData&lt;/code&gt; class stores patient data, medical history, and treatments, while the &lt;code&gt;AppointmentScheduler&lt;/code&gt; class handles appointment scheduling.&lt;/p&gt;

&lt;p&gt;With the single responsibility principle implemented, we have made the code more maintainable, testable, and reusable.&lt;/p&gt;

&lt;p&gt;Next up on the list is the oOpen/closed principle.&lt;/p&gt;

&lt;h2&gt;
  
  
  Open/Closed Principle
&lt;/h2&gt;

&lt;p&gt;The Open/Closed Principle (OCP) is another component of the SOLID principle that states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. In other words, we should be able to extend the behaviour of a class without modifying its source code. This principle promotes code reusability and maintainability.&lt;/p&gt;

&lt;p&gt;Let's continue with the healthcare application use case and demonstrate the open/closed principle using Python code. Suppose we have a class called &lt;code&gt;Billing&lt;/code&gt; that calculates the bill for the patient's treatment.&lt;/p&gt;

&lt;p&gt;This is how the &lt;code&gt;Billing&lt;/code&gt; class can be written without adhering to the open/closed principle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Billing:
    def __init__(self, patient, amount):
        self.patient = patient
        self.amount = amount

    def calculate_bill(self):
        # calculate bill based on treatment amount
        if self.patient.insurance == 'HMO':
            self.amount = self.amount * 0.8
        elif self.patient.insurance == 'PPO':
            self.amount = self.amount * 0.9

        return self.amount
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The preceding &lt;code&gt;Billing&lt;/code&gt; class violates the OCP principle because if we want to add a new type of insurance, we have to modify the source code of the &lt;code&gt;Billing&lt;/code&gt; class, which can introduce bugs and make the code difficult to maintain.&lt;/p&gt;

&lt;p&gt;To comply with the OCP principle, we can modify the &lt;code&gt;Billing&lt;/code&gt; class to use a strategy pattern. We can create an abstract &lt;code&gt;Insurance&lt;/code&gt; class and have specific insurance classes extend it. The &lt;code&gt;Billing&lt;/code&gt; class can then accept an instance of the &lt;code&gt;Insurance&lt;/code&gt;class, which will be used to calculate the bill.&lt;/p&gt;

&lt;p&gt;Let's create an &lt;code&gt;Insurance&lt;/code&gt; abstract class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from abc import ABC, abstractmethod

class Insurance(ABC):
    @abstractmethod
    def calculate_discount(self, amount):
        pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The preceding code defines an &lt;code&gt;abstract&lt;/code&gt; class with the name &lt;code&gt;Insurance&lt;/code&gt; using the Python standard library's &lt;code&gt;abc&lt;/code&gt; module, which stands for &lt;code&gt;Abstract Base Classes&lt;/code&gt;. The &lt;code&gt;ABC&lt;/code&gt; class serves as the base class for all other abstract classes.&lt;/p&gt;

&lt;p&gt;The&lt;code&gt;Insurance&lt;/code&gt; class contains a single &lt;code&gt;abstract&lt;/code&gt;method named &lt;code&gt;calculate_discount&lt;/code&gt;. An &lt;code&gt;abstract&lt;/code&gt; method is a method that is declared in the &lt;code&gt;abstract&lt;/code&gt; class but does not have an implementation. Instead, any subclass of the &lt;code&gt;Insurance&lt;/code&gt; class must provide an implementation for this method.&lt;/p&gt;

&lt;p&gt;In this case, the &lt;code&gt;calculate_discount&lt;/code&gt; method takes in an &lt;code&gt;amount&lt;/code&gt; parameter and returns a discounted &lt;code&gt;amount&lt;/code&gt; based on the specific insurance policy. By defining this method as &lt;code&gt;abstract&lt;/code&gt; in the &lt;code&gt;Insurance&lt;/code&gt; class, any concrete implementation of an insurance policy must provide its implementation of this method.&lt;/p&gt;

&lt;p&gt;Now, let's implement two insurance classes (&lt;code&gt;HMOPolicy&lt;/code&gt; and &lt;code&gt;PPOPolicy&lt;/code&gt;) that extend the &lt;code&gt;Insurance&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class HMOPolicy(Insurance):
    def calculate_discount(self, amount):
        return amount * 0.8

class PPOPolicy(Insurance):
    def calculate_discount(self, amount):
        return amount * 0.9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The preceding snippets define two &lt;code&gt;concrete&lt;/code&gt; classes&lt;code&gt;HMOPolicy&lt;/code&gt; and &lt;code&gt;PPOPolicy&lt;/code&gt;, which inherit from the abstract &lt;code&gt;Insurance&lt;/code&gt;class. Both &lt;code&gt;concrete classes implement the&lt;/code&gt;calculate_discount&lt;code&gt;method, providing their implementation of the method defined in the&lt;/code&gt;abstract&lt;code&gt;class. The&lt;/code&gt;HMOPolicy &lt;code&gt;class overrides the&lt;/code&gt;calculate_discount&lt;code&gt;method to provide a discount of 20% (0.8) on the given&lt;/code&gt;amount`. This means that if a patient is covered by an HMO insurance policy, they will receive a 20% discount on their medical bills.&lt;/p&gt;

&lt;p&gt;Likewise, the &lt;code&gt;PPOPolicy&lt;/code&gt; class overrides the &lt;code&gt;calculate_discount&lt;/code&gt; method to provide a discount of 10% (0.9) on the given amount. This means that if a patient is covered by a PPO insurance policy, they will receive a 10% discount on their medical bills.&lt;/p&gt;

&lt;p&gt;Finally, the modified Billing class now looks like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
class Billing:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, patient, amount, insurance_policy):&lt;br&gt;
        self.patient = patient&lt;br&gt;
        self.amount = amount&lt;br&gt;
        self.insurance_policy = insurance_policy&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def calculate_bill(self):
    # calculate bill based on treatment amount
    return self.insurance_policy.calculate_discount(self.amount)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The preceding code defines a &lt;code&gt;Billing&lt;/code&gt; class that takes three parameters in its constructor: &lt;code&gt;patient&lt;/code&gt;, &lt;code&gt;amount&lt;/code&gt;, and &lt;code&gt;insurance_policy&lt;/code&gt;. The &lt;code&gt;patient&lt;/code&gt; parameter is a string that represents the name of the patient, the &lt;code&gt;amount&lt;/code&gt; parameter is a numerical value that represents the treatment cost, and the &lt;code&gt;insurance_policy &lt;/code&gt;parameter is an object that implements the &lt;code&gt;Insurance&lt;/code&gt; class (or its subclass).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;calculate_bill()&lt;/code&gt; method calculates the patient's bill based on the amount of the treatment cost and the discount provided by the insurance policy. The method calls the&lt;code&gt; calculate_discount() &lt;/code&gt;method of the &lt;code&gt;insurance_policy&lt;/code&gt; object and passes the treatment cost &lt;code&gt;(self.amount)&lt;/code&gt; as a parameter to the method. The &lt;code&gt;calculate_discount()&lt;/code&gt; method of the &lt;code&gt;insurance_policy&lt;/code&gt; object calculates the&lt;code&gt; discount&lt;/code&gt; based on the type of insurance policy and returns the discounted amount. In short, the &lt;code&gt;Billing&lt;/code&gt; class calculates the patient's bill based on the treatment cost and the type of insurance policy they have.&lt;/p&gt;

&lt;p&gt;With the open/closed principle implemented, the &lt;code&gt;Billing&lt;/code&gt; class is easier to maintain and extend. We can now add new insurance types by creating new classes that extend the &lt;code&gt;Insurance&lt;/code&gt; class without modifying the source code of the &lt;code&gt;Billing&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;And that's not all with SOLID principles, we have next on the list, the Liskov substitution principle.&lt;/p&gt;

&lt;h2&gt;
  
  
  Liskov Substitution Principle
&lt;/h2&gt;

&lt;p&gt;The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program. In other words, if a function takes an object of a superclass as a parameter, it should also be able to accept objects of its subclasses without causing any errors or unexpected behaviours.&lt;/p&gt;

&lt;p&gt;Let's continue with the healthcare application example and demonstrate the Liskov substitution principle using Python code. Suppose we have a class called &lt;code&gt;Patient&lt;/code&gt; with a method called &lt;code&gt;pay_bill&lt;/code&gt; that pays the bill for the patient's treatment.&lt;/p&gt;

&lt;p&gt;Without Liskov substitution principle implemented, &lt;code&gt;Patient&lt;/code&gt; class could be written this way:&lt;br&gt;
&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
class Patient:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, name, balance):&lt;br&gt;
        self.name = name&lt;br&gt;
        self.balance = balance&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def pay_bill(self, amount):
    if self.balance &amp;gt;= amount:
        self.balance -= amount
        print(f"Paid {amount} for the treatment")
    else:
        print("Insufficient balance. Please add funds")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The above &lt;code&gt;Patient&lt;/code&gt; class violates the LSP principle because if we create a subclass that has a different implementation of the &lt;code&gt;pay_bill&lt;/code&gt; method, it may cause unexpected behaviours when passed into a function that expects an object of the &lt;code&gt;Patient&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;To adhere to the LSP principle, we can modify the &lt;code&gt;Patient&lt;/code&gt; class to have a more general behaviour for the &lt;code&gt;pay_bill&lt;/code&gt; method. We can create a new subclass called &lt;code&gt;InsuredPatient&lt;/code&gt; that extends the &lt;code&gt;Patient&lt;/code&gt; class and has its implementation of the &lt;code&gt;pay_bill&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Now, let's take a look at the modified &lt;code&gt;Patient&lt;/code&gt; and &lt;code&gt;InsuredPatient&lt;/code&gt; classes:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
class Patient:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, name, balance):&lt;br&gt;
        self.name = name&lt;br&gt;
        self.balance = balance&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def pay_bill(self, amount):
    self.balance -= amount
    print(f"Paid {amount} for the treatment")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;class InsuredPatient(Patient):&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, name, balance, insurance_policy):&lt;br&gt;
        super().&lt;strong&gt;init&lt;/strong&gt;(name, balance)&lt;br&gt;
        self.insurance_policy = insurance_policy&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def pay_bill(self, amount):
    discounted_amount = self.insurance_policy.calculate_discount(amount)
    super().pay_bill(discounted_amount)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;br&gt;
In the preceding modified code, we created a new subclass called &lt;code&gt;InsuredPatient&lt;/code&gt; that extends the &lt;code&gt;Patient&lt;/code&gt; class and has its implementation of the &lt;code&gt;pay_bill&lt;/code&gt; method. The &lt;code&gt;InsuredPatient&lt;/code&gt; class also accepts an instance of the &lt;code&gt;Insurance&lt;/code&gt; class, which will be used to calculate the discounted bill amount.&lt;/p&gt;

&lt;p&gt;By adhering to the Liskov substitution principle, we can now pass an object of the &lt;code&gt;InsuredPatient &lt;/code&gt;class into a function that expects an object of the &lt;code&gt;Patient&lt;/code&gt; class without causing any unexpected behaviours.&lt;/p&gt;

&lt;p&gt;Moving right along, we have the interface segregation principle to discuss.&lt;/p&gt;

&lt;h2&gt;
  
  
  Interface Segregation Principle
&lt;/h2&gt;

&lt;p&gt;The Interface Segregation Principle (ISP) states that clients should not be forced to depend on interfaces they do not use. This means that classes should not be forced to implement interfaces with methods that they do not need.&lt;/p&gt;

&lt;p&gt;In the context of the healthcare application, let's say we have an interface called &lt;code&gt;Treatment&lt;/code&gt; that defines a method called &lt;code&gt;treat_patient&lt;/code&gt; that takes a &lt;code&gt;Patient&lt;/code&gt; object as a parameter and performs some treatment on the patient.&lt;/p&gt;

&lt;p&gt;Here's an example of how the &lt;code&gt;Treatment &lt;/code&gt;interface can be written:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;class Treatment(ABC):&lt;br&gt;
    @abstractmethod&lt;br&gt;
    def treat_patient(self, patient: Patient):&lt;br&gt;
        pass&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;br&gt;
Now let's say we have two classes called &lt;code&gt;Surgery&lt;/code&gt; and &lt;code&gt;Medication&lt;/code&gt; that implement the &lt;code&gt;Treatment&lt;/code&gt; interface. The &lt;code&gt;Surgery&lt;/code&gt; class implements the &lt;code&gt;treat_patient&lt;/code&gt; method by performing surgery on the patient, while the &lt;code&gt;Medication&lt;/code&gt; class implements the &lt;code&gt;treat_patient&lt;/code&gt; method by administering medication to the patient.&lt;/p&gt;

&lt;p&gt;However, the problem with the above design is that not all patients require surgery or medication. For instance, a patient with a broken arm may only require a cast and not surgery or medication. Therefore, it would be better to create separate interfaces for each type of treatment.&lt;/p&gt;

&lt;p&gt;With the interface segregation principle followed, this is how the modified code looks like:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
class Surgery(ABC):&lt;br&gt;
    @abstractmethod&lt;br&gt;
    def perform_surgery(self, patient: Patient):&lt;br&gt;
        pass&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;class Medication(ABC):&lt;br&gt;
    @abstractmethod&lt;br&gt;
    def administer_medication(self, patient: Patient):&lt;br&gt;
        pass&lt;code&gt;&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now we have two separate interfaces - &lt;code&gt;Surgery &lt;/code&gt;and &lt;code&gt;Medication&lt;/code&gt;. These interfaces define methods that are specific to their respective treatments. This allows the classes that implement these interfaces to only implement the methods that they need, and not be forced to implement unnecessary methods.&lt;/p&gt;

&lt;p&gt;With the interface segregation principle adhered to, we have improved the modularity and maintainability of our code, making it easier to add new treatments in the future without impacting the existing code.&lt;/p&gt;

&lt;p&gt;Interestingly, the SOLID story doesn't end with the interface segregation principle, we still have the dependency inversion.&lt;/p&gt;

&lt;h2&gt;
  
  
  Dependency Inversion Principle Principle
&lt;/h2&gt;

&lt;p&gt;The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, both should depend on abstractions. In other words, the details should depend on the abstractions, not the other way around.&lt;/p&gt;

&lt;p&gt;In the context of the healthcare application, let's say we have  &lt;code&gt;HospitalManager&lt;/code&gt; class responsible for managing the treatments for all the patients in the hospital. This class currently has a dependency on the &lt;code&gt;Surgery &lt;/code&gt;and &lt;code&gt;Medication&lt;/code&gt; classes, which are low-level modules.&lt;/p&gt;

&lt;p&gt;To adhere to the dependency inversion principle, we need to introduce an abstraction between the &lt;code&gt;HospitalManager&lt;/code&gt; class and the &lt;code&gt;Surgery&lt;/code&gt; and &lt;code&gt;Medication&lt;/code&gt; classes. One way to achieve this is by defining an interface called &lt;code&gt;TreatmentStrategy&lt;/code&gt; that defines the &lt;code&gt;execute_treatment&lt;/code&gt; method:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
class TreatmentStrategy(ABC):&lt;br&gt;
    @abstractmethod&lt;br&gt;
    def execute_treatment(self, patient: Patient):&lt;br&gt;
        pass&lt;br&gt;
&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;br&gt;
Now, we can modify the &lt;code&gt;Surgery&lt;/code&gt; and &lt;code&gt;Medication&lt;/code&gt; classes to implement the &lt;code&gt;TreatmentStrategy&lt;/code&gt; interface:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
class Surgery(TreatmentStrategy):&lt;br&gt;
    def execute_treatment(self, patient: Patient):&lt;br&gt;
        # perform surgery on patient&lt;/p&gt;

&lt;p&gt;class Medication(TreatmentStrategy):&lt;br&gt;
    def execute_treatment(self, patient: Patient):&lt;br&gt;
        # administer medication to patient&lt;br&gt;
`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Next, we modify the &lt;code&gt;HospitalManager &lt;/code&gt;class to depend on the &lt;code&gt;TreatmentStrategy&lt;/code&gt; interface instead of the &lt;code&gt;Surgery&lt;/code&gt; and &lt;code&gt;Medication&lt;/code&gt; classes:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;br&gt;
class HospitalManager:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, treatment_strategy: TreatmentStrategy):&lt;br&gt;
        self.treatment_strategy = treatment_strategy&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def manage_treatment(self, patient: Patient):
    self.treatment_strategy.execute_treatment(patient)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;By doing this, we have inverted the dependency - the &lt;code&gt;HospitalManager &lt;/code&gt;class now depends on an abstraction &lt;code&gt;TreatmentStrategy&lt;/code&gt; instead of a low-level module &lt;code&gt;Surgery&lt;/code&gt; and &lt;code&gt;Medication&lt;/code&gt;. This makes the code more flexible and easier to maintain, as we can easily swap out different implementations of the &lt;code&gt;TreatmentStrategy&lt;/code&gt; interface without impacting the &lt;code&gt;HospitalManager&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;Overall, the dependency inversion principle helps to reduce coupling and improve the modularity and maintainability of our code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;SOLID principles are well-accepted software design principles. SOLID principles were developed to address software design challenges by providing a set of best practices for writing maintainable and scalable code. By following SOLID principles, software developers can create code that is easier to understand, easier to maintain, and more flexible in the face of changing requirements.&lt;/p&gt;

&lt;p&gt;Other design principles such as &lt;code&gt;GRASP&lt;/code&gt; (General Responsibility Assignment Software Patterns),&lt;code&gt; DRY &lt;/code&gt;(Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and &lt;code&gt;YAGNI&lt;/code&gt;(You Aren't Gonna Need It) are worth checking out to see how these design principles fit into your project requirements.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note:&lt;br&gt;
I published the original version on &lt;a href="https://tinyurl.com/446x3fnb"&gt;Hashnode&lt;/a&gt;. This copy is modified!&lt;/em&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>python</category>
      <category>beginners</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>How React flirts with data</title>
      <dc:creator>Olatunde Adedeji</dc:creator>
      <pubDate>Fri, 22 Jul 2022 16:05:00 +0000</pubDate>
      <link>https://dev.to/olatundeadedeji/how-react-flirts-with-data-4o2o</link>
      <guid>https://dev.to/olatundeadedeji/how-react-flirts-with-data-4o2o</guid>
      <description>&lt;p&gt;React is the Rolls Royce of frontend development inspiring greatness in designing user interfaces. Undoubtedly, React is a JavaScript library for building user interfaces. React focuses explicitly on building UI for web and mobile applications. React is so popular, flexible, and declarative- the React API does the heavy lifting for you in building user interfaces. React allows you to develop reusable components that are easy to read, scale and maintain. &lt;/p&gt;

&lt;p&gt;Essentially, React component consists of a markup mix of HTML, styled by CSS, and with smooth interactivity handled with the help of JavaScript. &lt;/p&gt;

&lt;p&gt;React has a large community of developers who are ready to help you all the way in learning and understanding the intricacies of React ecosystem. The die-hard React fans would tell you this is the best time to be a web developer- the wholesome developer experience is eccentric with a great feeling of nothing is impossible with user interface coding! &lt;/p&gt;

&lt;p&gt;However, in this article, we are going to learn how React handles data we use in web applications. Data is critical to every web application and React does excellently well in handling data, data in the component state, passing data from one component to another, and fetching data from an API data source. We will explore in specific how React handles data fetching using Fetch API. &lt;/p&gt;

&lt;h1&gt;
  
  
  Understanding data and its uni-directional flow
&lt;/h1&gt;

&lt;p&gt;Conventionally, data flows in one-way directional movement in React. It means there is only one source that the rest of your application components expect data to come from and that source is a parent component,  nowhere else. Technically, in React, data flows from the parent component to the child component. This flow is in form of props. Props are the carrier of component information. Data is not expected to flow from child to parent or child to child. This encourages a definite single source of truth for data. Why would React enforce the uni-directional flow of data? &lt;/p&gt;

&lt;p&gt;The reasons are not far-fetched: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;It is easier to debug, as we know where data is coming from. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Unidirectional data flow is less prone to errors, as we have more control over our data. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It is more efficient, as the library knows what the boundaries are of each part of the disparate system.  &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Data in the database
&lt;/h1&gt;

&lt;p&gt;Hardly will you see a web application without a backend service. Of course there are many benefits of keeping your data in a database. Firstly, data persistence improves user experience. Users of your web application will appreciate a system that makes storage and retrieval of data- users information a painless adventure. React shines with its controlled component form ability in capturing user inputs and relaying it back when needed with little or no latency. &lt;/p&gt;

&lt;p&gt;Secondly, we need to consider data security and how React rises to occasion. Data security starts from the point of data collection. Are users able to submit HTML contents to your backend service? If yes, are you using React best practices to ensure the right data in the right form get to your database? No developer is ever proud of a system vulnerable to SQL injection. SQL injection describes a scenario a playful or bad actor user exploit the vulnerability of your web applications in injecting exploitative SQL codes in your system that is capable at the extreme case, of  CRUD operations. Nobody wants this but you have to expect it and be defensive against SQL injection attacks in your development.  &lt;/p&gt;

&lt;p&gt;Imagine this gets to execute on your database from your form input fields:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;DROP&lt;/span&gt; &lt;span class="nx"&gt;TABLE&lt;/span&gt; &lt;span class="nx"&gt;IF&lt;/span&gt; &lt;span class="nx"&gt;EXISTS&lt;/span&gt; &lt;span class="nx"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Customers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It will definitely be embarrassing!  &lt;/p&gt;

&lt;p&gt;So, handling dangerous form data before the son of a bitch gets to your database is ever more important to retain your job as a developer and to maintain the good credibility of your company or clients. User data sanitization is critical and for React applications, an open source package such as &lt;a href="https://formik.org/" rel="noopener noreferrer"&gt;Formik&lt;/a&gt; helps reduce the burden of form development. You can even go the extra mile with what the package has to offer to be at the safer end of what goes into your database. &lt;/p&gt;

&lt;h1&gt;
  
  
  Concept of immutability
&lt;/h1&gt;

&lt;p&gt;Immutability makes data flow easier to understand in React applications. An immutable variable means its value cannot change after being created. Mutability and immutability are frequently used in programming in a rather confusing or probably complex way. &lt;/p&gt;

&lt;p&gt;Why are we not using simple terms like can change, modifiable (mutable) or cannot change, not modifiable (immutable)? &lt;/p&gt;

&lt;p&gt;These are rather easier to understand anyway this is by the way! Developers' communities are built around folks that love complex words- we are all in it together! &lt;/p&gt;

&lt;p&gt;Technically, JavaScript Strings value types are immutable. You can’t directly change its value but you can re-assign it to another value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;strings&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt;&lt;span class="nx"&gt;John&lt;/span&gt; &lt;span class="nx"&gt;Joel&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can’t do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;strings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fekrqoe9ybdfhdstu05lj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fekrqoe9ybdfhdstu05lj.png" alt="screenshot Strings immutability"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can only mutate string values with some methods like replace(), trim() etc &lt;/p&gt;

&lt;p&gt;React says do not mutate(change) the state property of a component directly. In essence, state values are immutable. But with a caveat, you can only change the state value with a function updater method- setState(). This help instils some sanity into the coding culture and makes debugging easier.  &lt;/p&gt;

&lt;p&gt;React unequivocally says, how you handle your data is up to you, even mutations. In large React applications, performance tends to be a major reason why we care so much about how data mutate. A change in states naturally can cause React components to re-render. You wouldn't want expensive re-rending to impair the performance of your React applications. In redux, a way to manage complex state data in React. You deal with state mutations through reducers not directly. So, immutability in React encourages a single source of truth of your data. You also tend to have cleaner codes with clarity of your functions' behaviour.  &lt;/p&gt;

&lt;h1&gt;
  
  
  Fetching data from an external data source
&lt;/h1&gt;

&lt;p&gt;Dealing with external data sources in React could be a no-brainer with the right approach. We are going to see how fetching data is loaded into React from an external source using a simple fetch(). &lt;/p&gt;

&lt;p&gt;Why fetch()? It is native to our browsers. It is right there on the window object- window.fetch. No need of extra package installation. You simply hit the ground running with your Http request handling in a promise based request approach. &lt;/p&gt;

&lt;p&gt;Let's make a simple GET request with fetch(). And all we have to do is to  include the URL endpoint to which we want to make our request in the Fetch() method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;useEffect&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;people&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setPeople&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;([]);&lt;/span&gt; 

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;isLoading&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setIsLoading&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  

    &lt;span class="nf"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 

        &lt;span class="c1"&gt;// GET request using fetch with  useEffect Hook &lt;/span&gt;

        &lt;span class="nf"&gt;setIsLoading&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 

        &lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;https://swapi.dev/api/people/&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 

            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; 

            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;setPeople&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;results&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; 

        &lt;span class="nf"&gt;setIsLoading&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  

    &lt;span class="c1"&gt;// Empty dependency array means this effect will only run once &lt;/span&gt;

    &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[]);&lt;/span&gt; 



    &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; 

        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; 

            &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;h5&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="nx"&gt;Get&lt;/span&gt; &lt;span class="nx"&gt;Data&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="nx"&gt;an&lt;/span&gt; &lt;span class="nx"&gt;API&lt;/span&gt; &lt;span class="nx"&gt;Data&lt;/span&gt; &lt;span class="nx"&gt;Source&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/h5&amp;gt;&lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;isLoading&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="nx"&gt;Loading&lt;/span&gt; &lt;span class="nx"&gt;people&lt;/span&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/p&amp;gt;: people.map&lt;/span&gt;&lt;span class="se"&gt;(&lt;/span&gt;&lt;span class="sr"&gt;person =&amp;gt; &amp;lt;p key={person.name}&amp;gt;{person.name},{person.mass}, {person.height}&amp;lt;/&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)}&lt;/span&gt;            &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; 

                &lt;span class="p"&gt;{}&lt;/span&gt; 



            &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
        &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt; 

&lt;span class="p"&gt;}&lt;/span&gt;  

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s quickly break the code down: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We import useState and useEffect Hooks to bring them to scope in our applications. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The const [people, setPeople] = useState([])  and the const [isLoading, setIsLoading] = useState(true) were set to manage people and isLoading states &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We then have useEffect to handle the logic of data fetching from the endpoint &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The endpoint URL was passed as parameter to  fetch('&lt;a href="https://swapi.dev/api/people/'" rel="noopener noreferrer"&gt;https://swapi.dev/api/people/'&lt;/a&gt;) &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The .then() callback returns a new promise with the conversion of response to a JSON  data &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The second .then() callback assign the JSON response data to our state variable-people &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We then call on the map() to iterate on the arrays of people objects returned. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  In conclusion,
&lt;/h1&gt;

&lt;p&gt;We can see that React shines well among peers in handling data in any web application of any size and complexity. Its uni-directional data flow enables developers to understand where data is coming from and what it is capable of becoming, thus makes debugging easier. &lt;/p&gt;

&lt;p&gt;The immutability concepts in React applications optimizes complex applications for better performance. You then ensure you are developing pure components with predictable behaviour since you know how your variables, arrays and objects might behave. &lt;/p&gt;

&lt;p&gt;Finally, the understanding of React ability to flirt with data will not be complete without making refence to how React handles data from a data source, a daily application development task for every professional developer. React library for building user interface handle data with a touch of class.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>A Succinct Explanation of React.useEffect() Hook</title>
      <dc:creator>Olatunde Adedeji</dc:creator>
      <pubDate>Mon, 18 Jul 2022 16:30:00 +0000</pubDate>
      <link>https://dev.to/olatundeadedeji/a-succinct-explanation-of-reactuseeffect-hook-3eo4</link>
      <guid>https://dev.to/olatundeadedeji/a-succinct-explanation-of-reactuseeffect-hook-3eo4</guid>
      <description>&lt;p&gt;React.useEffect() is one of the coolest dudes among React Hooks. If you have been hooked into the world of functional components, this will definitely look familiar else you are probably still deep-necked down into the legacy React applications. You might need some functional React components pills! I must say the team behind React library are aggressively advocating for the use of functional and the Hooks approach to React applications development. It is certainly worth the effort going the Hooking way! &lt;/p&gt;

&lt;p&gt;Anyway, useEffect helps React developers appear smarter than they are, taking care of side effects in functional React components with its simplistic touch of syntax constructs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="err"&gt;“&lt;/span&gt;&lt;span class="nx"&gt;Runing&lt;/span&gt; &lt;span class="nx"&gt;side&lt;/span&gt; &lt;span class="nx"&gt;effects&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;span class="p"&gt;})&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: This runs every time component renders! You might not want this in reality. &lt;/p&gt;

&lt;p&gt;If you like hooking up (no pun intended)- I mean with functional components, I am here to explain how you can do it well with the right understanding. In this article, you will learn and understand how, plus when to use useEffect() Hook. &lt;/p&gt;

&lt;h1&gt;
  
  
  What is a Hook?
&lt;/h1&gt;

&lt;p&gt;Hooks are special function that allow you to hook into React state and lifecycle methods in functional components. Basically, functional and class approaches are the two major ways to develop a component in React.  Hooks work only with the functional components approach. If you stumble on any Hooks in a class component, kindly raise genuine alarm. Something is definitely wrong. &lt;/p&gt;

&lt;h1&gt;
  
  
  useEffect() handles side effects
&lt;/h1&gt;

&lt;p&gt;The purpose of useEffect() is to handle and mange side effects. And what are these side effects? Side effects are any operation in a function that is not directly related to the final output of the function. If you have probably wanted to fetch data from an API or other data source, ever wanted to tinker with DOM manually in React applications or have a subscription service set up to listen to an emitted event, all these and more are side effects in real life React. &lt;/p&gt;

&lt;p&gt;Let‘s take a look at this side-effect of a function using &lt;em&gt;document.title&lt;/em&gt; to display name information on a browser.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt; 

    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; 

   &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;SayGreeting&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Olatunde&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;/&amp;gt;&lt;/span&gt; 

  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
  &lt;span class="p"&gt;);&lt;/span&gt; 

&lt;span class="p"&gt;}&lt;/span&gt; 

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;SayGreeting&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greeting&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;`You welcome, &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;!`&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 

  &lt;span class="c1"&gt;// Side-effect with DOM manipulation! &lt;/span&gt;

  &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;`Greetings to &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 

  &lt;span class="c1"&gt;// Main expected function output &lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;greeting&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;;&lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; 

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the preceding snippet, we have a component SayGreeting with a side effect of  document.title = &lt;code&gt;Greetings to ${name}&lt;/code&gt;; This is obviously a wrong way to add a side-effect to a component. You would rather hand this over to useEffect to handle. &lt;/p&gt;

&lt;p&gt;Let's refactor our snippet with useEffect () to manage the side effect of the component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;SayGreeting&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greeting&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;`You welcome, &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;! `&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  

   &lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;   

   &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;`Greetings to &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;//Side-effect with DOM manipulation inside useEffect()!  &lt;/span&gt;

  &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;  

  &lt;span class="c1"&gt;// Main expected function output  &lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;greeting&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;; &lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Essentially, components are the basic building block of any React application.  So, for any expression of a user interface, at least a component is rendered. The useEffect() can be used to handle the logical part of component while allowing the component to focus on the rendering part. And since we can’t tell React how many times a component should be rendered, we can clearly control how the side effects of any component should be handled in case a component chooses to render multiple times. We can control how the side effects of a component are managed with the useEffect() optional dependency argument. &lt;/p&gt;

&lt;p&gt;Intrinsically, a component is capable of two things:  rendering and handling side-effects. It is always the best practice to leave the handling of side effects to useEffect().  &lt;/p&gt;

&lt;h1&gt;
  
  
  How to pass argument to useEffect()
&lt;/h1&gt;

&lt;p&gt;The useEffect() hook graciously accepts two arguments: useEffect(callback, [dependencies]); &lt;/p&gt;

&lt;p&gt;*The callback is the function containing the side-effect logic.  &lt;/p&gt;

&lt;p&gt;*The dependency represents optional array of dependency or dependencies.The useEffect() executes callback every time the dependencies change. &lt;br&gt;
This explains the default scenario of useEffect()&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  
    &lt;span class="c1"&gt;// Runs every time the component renders  &lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;  

&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  
    &lt;span class="c1"&gt;// Runs only on initial render  &lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[])&lt;/span&gt; &lt;span class="c1"&gt;// Optional second argument: dependency array  &lt;/span&gt;

&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  
    &lt;span class="c1"&gt;// Runs only when 'OptionalDataValue' changes  &lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;OptionalDataValue&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Fetching data from an endpoint over a network
&lt;/h1&gt;

&lt;p&gt;Let’s dive into how the useEffect() performs data fetching side effect. &lt;/p&gt;

&lt;p&gt;The following component FetchUsers  fetches the users list over a specified endpoint on the network:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;,{&lt;/span&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt; 

    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;  

   &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;FetchUsers&lt;/span&gt; &lt;span class="o"&gt;/&amp;gt;&lt;/span&gt; 

  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
  &lt;span class="p"&gt;);&lt;/span&gt; 

&lt;span class="p"&gt;}&lt;/span&gt;  

  &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;FetchUsers&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;users&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setUsers&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;([]);&lt;/span&gt;  

    &lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  

      &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;fetchUsers&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  

        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;fetch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt; https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  

        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fetchedUsers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  

        &lt;span class="nx"&gt;setUsers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;fetchedUsers&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  

      &lt;span class="p"&gt;}&lt;/span&gt;  

      &lt;span class="nx"&gt;fetchUsers&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;  

    &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;users&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt; 

     &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;  

      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;  

        &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;users&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt; &lt;span class="nx"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="se"&gt;)&lt;/span&gt;&lt;span class="sr"&gt;} &lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt; &lt;/span&gt;&lt;span class="err"&gt; 
&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;  

   &lt;span class="p"&gt;}&lt;/span&gt;  

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The useEffect() starts a fetch request by calling an async function fetchUsers() after the initial componentDidMount. &lt;/p&gt;

&lt;p&gt;When the request completes, setUsers(fetchedUsers) updates the users current state with the already fetched users list. &lt;/p&gt;

&lt;p&gt;We set an empty array [] dependency to indicate the useEffect() should run once component is mounted and if any dependency was added to the array which could be a prop or state value-[users].  We will only re-run the useEffect() once the users list changes.&lt;/p&gt;

&lt;h1&gt;
  
  
  useEffect() and Component lifecycle methods
&lt;/h1&gt;

&lt;p&gt;Components in React undergo three major phases; mounting, updating and unmounting. This explains the relationship of component with the DOM tree. You should be familiar with how React use Virtual DOM on top of the native browser DOM to smartly update the DOM on any state change. This is one of the innovative ideas of React.  &lt;/p&gt;

&lt;p&gt;So, when the component is mounted on the DOM, componentDidMount() is invoked to perform its side effect operation which could be network requests or mutations in the DOM as explained earlier.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;componentDidMount&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 

&lt;span class="nx"&gt;Console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="err"&gt;“&lt;/span&gt;&lt;span class="nx"&gt;component&lt;/span&gt; &lt;span class="nx"&gt;mounted&lt;/span&gt; &lt;span class="nx"&gt;successfully&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 

 &lt;span class="p"&gt;}&lt;/span&gt; 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The useEffect() encapsulates the componentDidMount(), componentDidUpdate() and componentWillUnmount() &lt;/p&gt;

&lt;p&gt;We will be examining how the  useEffect() handle stages in the component lifecycle methods. &lt;/p&gt;

&lt;h1&gt;
  
  
  Component did mount
&lt;/h1&gt;

&lt;p&gt;With componentDidMount():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;componentDidMount&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 
&lt;span class="p"&gt;};&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This runs when the component mount and it runs on every component re-rendering. &lt;/p&gt;

&lt;p&gt;We can also look at this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;componentDidMount&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[]);&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the preceding, an empty second argument array is passed. This means when the component mount and the useEffect() runs once as well. This doesn’t re-run the useEffect() at every re-rendering. &lt;/p&gt;

&lt;h1&gt;
  
  
  Component will update
&lt;/h1&gt;

&lt;p&gt;With componentWillUpdate():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;componentWillUpdate&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 

 &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second argument is passed to the useEffect() and any state or props value change will cause the component to update. &lt;/p&gt;

&lt;h1&gt;
  
  
  Component will unmount
&lt;/h1&gt;

&lt;p&gt;With componentWillUnmount():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 

 &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;componentWillUnmount&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 

  &lt;span class="p"&gt;};&lt;/span&gt; 

 &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;args&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the return function running after the side effect, you have a cleanup mechanism to handle the side effect before being re-mounted. &lt;/p&gt;

&lt;h1&gt;
  
  
  In conclusion,
&lt;/h1&gt;

&lt;p&gt;The useEffect is an important Hook in functional component. We have  seen how useEffect() helps with handling of side-effects. Apart from managing  side effects, useEffect() Hook enables us to further separate concerns within the component by handling the logical code in component while component faces the task of rendering. &lt;/p&gt;

&lt;p&gt;Also with useEffect Hook, we have a lean way of capturing component lifecycles and methods in our React applications regardless of  components complex states. &lt;/p&gt;

&lt;p&gt;Kindly let me know what you feel about the information on useEffect() Hook, is there any over look concepts or not too clear explanation of useEffect() Hook. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>api</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Hello, I'm Olatunde Adedeji</title>
      <dc:creator>Olatunde Adedeji</dc:creator>
      <pubDate>Sun, 29 May 2022 17:15:59 +0000</pubDate>
      <link>https://dev.to/olatundeadedeji/hello-im-olatunde-adedeji-2h71</link>
      <guid>https://dev.to/olatundeadedeji/hello-im-olatunde-adedeji-2h71</guid>
      <description>&lt;p&gt;I have been coding for over 6 years.&lt;/p&gt;

&lt;p&gt;You can find me on Twitter as @OAAdedeji&lt;/p&gt;

&lt;p&gt;I live in Lagos, Nigeria.&lt;/p&gt;

&lt;p&gt;I work for Mowebsite as a Full-Stack Engineer. &lt;/p&gt;

&lt;p&gt;I mostly program in HTML, CSS, JavaScript, React, Gatsby, Python &amp;amp;&amp;amp; PHP.&lt;/p&gt;

&lt;p&gt;I am currently accumulating knowledge more about the serverless web and JAM stack ecosystem while implementing things I have learned in regards to startups -HealthTech, FinTech and product leadership.&lt;/p&gt;

&lt;p&gt;Nice to meet you.&lt;/p&gt;

</description>
      <category>introduction</category>
    </item>
  </channel>
</rss>
