<?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: KevinZ-CS</title>
    <description>The latest articles on DEV Community by KevinZ-CS (@kevinzcs).</description>
    <link>https://dev.to/kevinzcs</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%2F892577%2Fb4123255-3ee5-4bf4-a11c-502104d49bb4.png</url>
      <title>DEV Community: KevinZ-CS</title>
      <link>https://dev.to/kevinzcs</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/kevinzcs"/>
    <language>en</language>
    <item>
      <title>Redux Explained</title>
      <dc:creator>KevinZ-CS</dc:creator>
      <pubDate>Sun, 05 Feb 2023 05:14:31 +0000</pubDate>
      <link>https://dev.to/kevinzcs/redux-explained-11ig</link>
      <guid>https://dev.to/kevinzcs/redux-explained-11ig</guid>
      <description>&lt;p&gt;In this blog we will be discussing what exactly is redux and how it works under the hood when using a redux library. So what is redux? Redux is a library that is used to help manage an application's global state. It allows state to be managed in a way that's more predicable and scales well to larger applications. So what exactly does this all mean? Well in order to understand this definition we must first understand the three core principles when it comes to redux which is as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Single Source of Truth &lt;/li&gt;
&lt;li&gt;State is Read Only&lt;/li&gt;
&lt;li&gt;Changes are made with pure functions&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Single Source of True and Data Flow
&lt;/h2&gt;

&lt;p&gt;So to elaborate on the first principle, redux focuses on a single source of truth. This single source of truth is referred to as a store where the state of an application lives. Normally when using a framework like react, state is shared between components by passing them as props. But with redux every component can access the state via store without the need to pass props. This greatly simplifies the architecture of the application and results in neater and more predicable code. &lt;/p&gt;

&lt;h2&gt;
  
  
  State is Read Only
&lt;/h2&gt;

&lt;p&gt;When we say state is read only we mean that the only way to change the state is to emit an action. The keyword to remember here is action. An action is an object that describes what happened. In other words, actions describe how a state should be updated. From a code standpoint actions are used with a dispatch function which is made available to the application via store. When the dispatch function is called it signals that the user wants to update a state and in order to know the instructions on how to update the state, an action is passed in as an argument. Within the dispatch function the reducer function is then called with the action as an argument. (more on reducers in the next section)&lt;/p&gt;

&lt;h2&gt;
  
  
  Changes are made with pure functions
&lt;/h2&gt;

&lt;p&gt;As mentioned in the previous section, in redux there is a function called a reducer. A reducer is a pure function in the sense that it is a function that only returns a value and has no side effects. So what exactly does this reducer function do? Well the reducer function takes in 2 arguments, the current state and an action, and returns an updated state.&lt;/p&gt;

&lt;h2&gt;
  
  
  Putting it all together
&lt;/h2&gt;

&lt;p&gt;Now that we've gone over how redux works conceptually lets see an example. We are going to manually create functions that replicates the functionality of the redux library to illustrate what is going on under the hood.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createStore(reducer) {
   let state;

   function getState() {
       return state
   }

   function dispatch(action) {
       state = reducer(state, action)
   }


   dispatch({ type: "@@init" })

   return { getState, dispatch }
}

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

&lt;/div&gt;



&lt;p&gt;In the above code we are replicating a store by creating a store function. As mentioned previously, a store is where state lives and also provides access to the dispatch function. This is shown within the store function where we initiate a state variable and provide a getState function that simply returns that variable. Then we have a dispatch function that takes in an action as an argument which is then passed into the reducer along with the current state. The reducer function returns an updated value that is then assigned to the state variable. &lt;/p&gt;

&lt;p&gt;Finally, the createStore function will return an object that contains the getState and dispatch functions which can be access through dot notation like any other object. A brief side note, the dispatch function is also called within the store with the init action as you might have noticed. This is added so that when the store is initially accessed, render within dispatch will be called and assigned an initial value to the initiated but undefined state variable. (This will be clearer once we look at an example of a reducer function). &lt;/p&gt;

&lt;p&gt;Now lets look at the reducer function within dispatch. Here is an example of what a reducer function might look like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState = {
   count: 0,
   running: true
}


function reducer(state = initialState, action) {
   switch (action.type) {
       case "increment":
           return {
               ...state,
               count: state.count + 1
           }
       case "decrement":
           return {
               ...state,
               count: state.count - 1
           }
       default:
           return state
   }
}

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

&lt;/div&gt;



&lt;p&gt;Besides having the job of taking in a state and action, the reducer is also responsible for setting an initial value for the state. In this case we define an initialState variable and set that as the default value for the state argument which ties in with the previous example and explains why we initiated the state variable in the store but left it undefined. &lt;/p&gt;

&lt;p&gt;Next we have the switch statement where a case will run depending on the action type. For example, lets say we call the dispatch function and pass in an action with the type "increment". In our reducer, we will hit the "increment" case and update our state based on that case and return the updated state. At the end of our switch statement we also have a default value where we simply just return the state if the action matches none of our cases. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;As stated before the above code simply just gives an idea of what occurs under the hood. The redux library provides alternative ways to access these functionalities without needing to manually write out some of the above code such as the getState or dispatch function. Once the redux library is imported and your application is set up accordingly all the redux related functions will become available and can be accessed using specific keywords. Redux is an incredibility useful library and we only just covered the foundation! Hope this helps with your redux journey!&lt;/p&gt;

</description>
      <category>cryptocurrency</category>
      <category>crypto</category>
      <category>web3</category>
      <category>offers</category>
    </item>
    <item>
      <title>CRUD with Rails</title>
      <dc:creator>KevinZ-CS</dc:creator>
      <pubDate>Wed, 21 Dec 2022 05:43:44 +0000</pubDate>
      <link>https://dev.to/kevinzcs/crud-with-rails-32aa</link>
      <guid>https://dev.to/kevinzcs/crud-with-rails-32aa</guid>
      <description>&lt;p&gt;In this blog we will be going over CRUD features in rails. The first question you may ask is what is CRUD? CRUD is an acronym that stands for create, read, update, and delete. With these actions a user can interact with a database in our rails backend and send over a response to the frontend. &lt;/p&gt;

&lt;h2&gt;
  
  
  Read
&lt;/h2&gt;

&lt;p&gt;To start off, we will be covering the read action from CRUD. This action is actually split into two separate actions, index and show. Both are similar in the sense that they respond to a GET request from the frontend. The main difference is that index responds with a collection of data while show responds with a specific piece of data. &lt;/p&gt;

&lt;p&gt;To get this properly set up with rails in the backend you will need to first set up routes with actions assigned to it. This should look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rails.application.routes.draw do
  get '/games', to: 'games#index'
  get '/games/:id', to: 'games#show'
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see this route receives a get request from the frontend at the games route. The second half of the route addresses the controller and action that will be handling that request. So in our example the games controller will be handling our get request using the index and show action. &lt;/p&gt;

&lt;p&gt;One thing you may notice is the :id that is part of the second route with the show action. Remember, as previously mentioned the show action unlike index will only respond with a single specific piece of data. That id is meant to identify that specific data and is included in the url of the fetch request from the frontend. From that url that id will be captured in an object called params at the backend and this will be used in the controller as you will soon see. &lt;/p&gt;

&lt;p&gt;So in the games controller you would see something like 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 GamesController &amp;lt; ApplicationController

  # GET /games
  def index
    games = Games.all
    render json: games
  end

  # GET /games/:id
  def show
    game = Game.find_by(id: params[:id])
    render json: game
  end

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

&lt;/div&gt;



&lt;p&gt;As you can see the index action will grab all games from the database and store it in the games variable and send a response that contains all the games data in json format. &lt;/p&gt;

&lt;p&gt;In the show action notice how we are looking for a specific piece of data based on the id attribute using the value (obtained from the url of the fetch request) thats stored in the params object. Again that data will be stored in a variable and sent to the frontend as a response in json format.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create
&lt;/h2&gt;

&lt;p&gt;Next, we will discuss the create action. The create action uses data from the frontend via params object to create new data and then save it to the database. Like before, to set this up we will need to add a route associated with the create action. So in our routes file it should look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rails.application.routes.draw do
  post '/games', to: 'games#create'
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, this route receives a post request from the frontend at the games route which will use the create action in the games controller to handle the request. In the games controller it should look something like 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 GamesController &amp;lt; ApplicationController

  # POST /game
  def create
  game = Game.create(name: params[:name], price: 
  params[:price])
  render json: game, status: :created
  end

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

&lt;/div&gt;



&lt;p&gt;Notice how we're using the params object again in this action. In order to create and save data in our database in our backend we need information on what to create. This information comes from the frontend request. In a post request we include data in the body of the request. In this case the body of our request would include the name and price of the game. Once that request has been received at the backend, data from the body of the request is then saved into the params object which can then be used in our create method to create and save new data into our database. &lt;/p&gt;

&lt;h2&gt;
  
  
  Update
&lt;/h2&gt;

&lt;p&gt;Next, we have the update action. The update action is used (as the name suggests) to update existing data in our database. Like the other actions we will need to create a route that's associated with this action. In our routes file it should look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rails.application.routes.draw do
  patch '/games/:id', to: 'games#update'
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This route receives a patch request from the frontend at a route that contains the id of the data that we want to update and the request will be handled with an update action in the games controller. The games controller should look something like 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 GamesController &amp;lt; ApplicationController

  # PATCH /game
  def update
  game = Game.find_by(id: params[:id])
  game = Game.update(name: params[:name], price: 
  params[:price])
  render json: game
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example we are using the params object again but this time it contains more data than before. The params contain the id from the url as well as the updated data in the body of the patch request sent from the frontend. With that in mind, the update action will use the id from the params object to find the specific data that will be updated and updates it with the new data sent from the body of the patch request. Finally, the updated game will be sent back to the frontend in json format. &lt;/p&gt;

&lt;h2&gt;
  
  
  Delete
&lt;/h2&gt;

&lt;p&gt;Lastly, we have the delete request which uses the destroy action in the backend. We set up our route for this action like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rails.application.routes.draw do
  delete '/games/:id', to: 'games#destroy'
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Delete requests from the frontend will be sent to this route and handled with the destroy action in the games controller. We have an id in the route because we are expecting to delete a specific data with that id which should be present in the fetch request url. In the games controller it should look something like 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 GamesController &amp;lt; ApplicationController

  # DELETE /games/:id
  def destroy
    game = Game.find_by(id: params[:id])
    head :no_content
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this action we are simply finding a specific data with the id stored in the params object and then deleting it from the database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In summary, from the backend perspective you will need a routes file to perform CRUD. In the routes file each route will need a http verb (type of request: get, patch, delete etc.), the route, as well as the controller and action that will be handling the request. You will also need to make sure that the actions in the controller file is handling the request correctly and returning the appropriate data. Hope this helps!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Object-Oriented Programming in Ruby Explained</title>
      <dc:creator>KevinZ-CS</dc:creator>
      <pubDate>Sun, 06 Nov 2022 03:19:56 +0000</pubDate>
      <link>https://dev.to/kevinzcs/object-oriented-programming-in-ruby-explained-17o6</link>
      <guid>https://dev.to/kevinzcs/object-oriented-programming-in-ruby-explained-17o6</guid>
      <description>&lt;p&gt;What is object-oriented programming(OOP)? This is a common interview question that most developers will be asked when interviewing for a developer role. OOP is essentially a style of programming that is best characterized by four core concepts which includes, encapsulation, inheritance, abstraction, and polymorphism. In this blog we will address each of the four core concepts using ruby code. &lt;/p&gt;

&lt;h2&gt;
  
  
  Encapsulation
&lt;/h2&gt;

&lt;p&gt;In programming encapsulation is when we group related variables and methods that operate on them into objects. An example of this would be Ruby classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Dog

  def bark
    'bark bark'
  end

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

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Cat

  def meow
    'meow'
  end

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

&lt;/div&gt;



&lt;p&gt;In the example above we have a Dog class(an object). Now depending on how they are defined, anything defined within the Dog class can either be accessed by the Dog class itself or instances of the Dog class. Currently, the Dog class contains a method called bark that returns the string 'bark bark'. If we were to create a separate Cat class that is completely unrelated to the Dog class then that Cat class and any instances of the Cat class itself cannot access any of the variables and methods defined within Dog. In this example it makes perfect sense since a cat does not bark. The advantage of modularizing code based on related data makes it easier for developers to organize and write cleaner code. &lt;/p&gt;

&lt;h2&gt;
  
  
  Inheritance
&lt;/h2&gt;

&lt;p&gt;What if there is a relationship between 2 classes? For example, lets say we have another class called Animal. Like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Animal

  def this_is_an_animal
      'I am an animal.'
  end

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

&lt;/div&gt;



&lt;p&gt;Well a dog is an animal so it only makes sense that the Dog class have access to the this_is_an_animal method and anything else defined in the Animal class. We can establish this relationship by making Dog a subclass of Animal by using the following syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Dog &amp;lt; Animal

  def bark
    'bark bark'
  end

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

&lt;/div&gt;



&lt;p&gt;Using the syntax &amp;lt;, Dog is currently the the subclass of the superclass Animal and inherits the characteristics of Animal, in this case includes the this_is_an_animal method. Using the example of the Cat class before, Cat is unrelated to Dog but is related to Animal since it is indeed an animal. The advantage of inheritance is that it eliminates redundant code. In this case, rather than writing the this_is_an_animal method in each of the Dog and Cat class we can simply define it once in the Animal class and have Dog and Cat inherit from Animal. &lt;/p&gt;

&lt;h2&gt;
  
  
  Abstraction
&lt;/h2&gt;

&lt;p&gt;In OOP abstraction pertains to the concept of only introducing relevant data about an object and hides everything else. In practice this concept can be understood through the use of private methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Restaurant 

    public

    def server 
        "Here's your food."
        chef
    end

    private 

    def chef 
        "Food"
    end
end


# creating a customer object of class Restaurant 
customer = Restaurant.new

# calling the public method of class server 
customer.server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example we've created a Restaurant class that contains a public method called server and a private method called chef. Using the concept of a Restaurant as an example, a customer interacts with the server and usually never interacts with the chef throughout his/her experience at the Restaurant. The server takes the customer's order and then interacts with the chef who provides the server with the food which is then brought to the customer by the server. &lt;/p&gt;

&lt;p&gt;The methods in the Restaurant class represent just that. The chef is a private method within the Restaurant class. As a private method the chef cannot be accessed directly outside the Restaurant class but can be accessed anywhere within the class, in this case by the server. Then the customer instance outside of the Restaurant class can call the server for their food. From a customer perspective there is no need to interact with the chef method since the server takes our order and brings us the food. We only expose the relevant method server outside the Restaurant class and hide the non-relevant chef method within the class.&lt;/p&gt;

&lt;p&gt;So why go through the trouble of abstracting this code? The two main benefits is that it makes the interaction with the class simpler and helps reduce the impact of change. For our example, in terms of simplicity the customer limited his/her interaction with just the server which is simple enough. In terms of reducing the impact of change, now imagine at a restaurant that a chef not only makes the food for the customer but takes the orders as well and in this example let's say multiple customers decides to change their order. This can potentially be disastrous if the chef changes the wrong orders. Multiple tables can potentially get the wrong order out of the entire restaurant and nobody would know who ordered what. But if we had a server, we would be able to figure out the customers order quicker in the event of a mistake since each server has their own assigned tables and we would simply need to limit our search to those tables compared to the entire restaurant.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Polymorphism
&lt;/h2&gt;

&lt;p&gt;Poly means many. Morph means form. So polymorphism means many forms. In OOP polymorphism is a technique that allows you to get rid of long if and else or switch and case statements. It does this by allowing one to execute the same method using different objects and obtain different results based on the different input objects. Below you will see polymorphism in its simplest form using inheritance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Class Animal
    def message
        'This is an animal.'
    end
end

class Dog &amp;lt; Animal
    def message
        'bark bark'
    end
end

class Cat &amp;lt; Animal
    def message
        'Meow'
    end
end

# Creating object 
animal = Animal.new
animal.message

# Creating different object calling same function 
animal = Dog.new
animal.message

# Creating different object calling same function 
animal = Cat.new
animal.message
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, although we are calling the same method message 3 times, the output each time will be different due to the rules of inheritance. In inheritance, if there is a method in the superclass that has the same name as the method in the current class, then the method in the current class overrides the one in the superclass by default. Since each class has their own version of the method message the output will be different depending on which object calls message. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In summary, it is safe to say that OOP is designed to make the jobs of developers easier. Using encapsulation we group related variables and functions together and this way we reduce complexity and be able to reuse this object in different parts of a program or in different programs. With abstraction we hide the details and the complexity and show only the essentials. This technique reduces complexity and also isolates the impact of changes in the code. With inheritance we can eliminate redundant code. Finally, with polymorphism we can refactor ugly switch case statements.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.geeksforgeeks.org/ruby-encapsulation/"&gt;https://www.geeksforgeeks.org/ruby-encapsulation/&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.geeksforgeeks.org/ruby-inheritance/"&gt;https://www.geeksforgeeks.org/ruby-inheritance/&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.geeksforgeeks.org/data-abstraction-in-ruby/"&gt;https://www.geeksforgeeks.org/data-abstraction-in-ruby/&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.geeksforgeeks.org/polymorphism-in-ruby/"&gt;https://www.geeksforgeeks.org/polymorphism-in-ruby/&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>ruby</category>
    </item>
    <item>
      <title>2 React Hooks That Every Beginner Should Know</title>
      <dc:creator>KevinZ-CS</dc:creator>
      <pubDate>Mon, 19 Sep 2022 23:53:03 +0000</pubDate>
      <link>https://dev.to/kevinzcs/2-react-hooks-that-every-beginner-should-know-125p</link>
      <guid>https://dev.to/kevinzcs/2-react-hooks-that-every-beginner-should-know-125p</guid>
      <description>&lt;p&gt;A React Hook is a JavaScript function that lets you "hook into" React state and lifecycle features from functional components. It was first introduced in React 16.8 and provides an alternative to writing class-based components. While legacy projects use class components, most of modern React development uses functional components which utilizes hooks that allows developers to write clearer and more concise code.&lt;/p&gt;

&lt;p&gt;In this blog post we will be going over 2 useful hooks that every beginner should know when first learning React. Namely, the State Hook and Effect Hook will be covered below.&lt;/p&gt;

&lt;h2&gt;
  
  
  State Hook
&lt;/h2&gt;

&lt;p&gt;In React, a state is a piece of data that is dynamic within a component. It stores data that is subject to change based on how users interact with the application. Below is an example of how a state is initiated in React and how it can be used in a component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;You clicked {count} times&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;
        Click me
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To initiate a React state we first import the useState function and then call the function while passing in an initial state (initial value in this case is 0). This function call will return an array with 2 elements with the first being the value of the initial state and the second being a function used to update the state. We then de-structure the array creating 2 new variables that can readily be used in our component. The count variable contains the current state while the setCount variable contains the function that updates the current state. &lt;/p&gt;

&lt;p&gt;In this case we are updating the state through the onClick event handler. Every time the user clicks on the button, 1 gets added to the current state and that new value gets passed into the setCount function which updates the current state to the new value. So with an initial state of 0, after clicking the button one time the current state updates to 1 since 1 + 0 = 1. As soon as the state updates, the entire component re-renders and new state of 1 will be reflected within the p tag and displayed to the user.&lt;/p&gt;

&lt;h2&gt;
  
  
  Effect Hook
&lt;/h2&gt;

&lt;p&gt;The Effect Hook is a React hook that causes a side effect when the component renders. It looks something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect } from "react";

function DogPics() {
  const [images, setImages] = useState([]);

  useEffect(() =&amp;gt; {
    fetch("https://dog.ceo/api/breeds/image/random/3")
      .then((r) =&amp;gt; r.json())
      .then((data) =&amp;gt; {
        // setting state in the useEffect callback
        setImages(data.message);
      });
  });

  return (
    &amp;lt;div&amp;gt;
      {images.map((image) =&amp;gt; (
        &amp;lt;img src={image} key={image} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To initiate the hook we first import the useEffect function from the React library and then we call it while passing in a callback function. UseEffect will then be called when the component renders and the side effect will be based on the callback function that was passed in. A common use for useEffect is fetching data from an API and storing it in a state when the component renders. &lt;/p&gt;

&lt;p&gt;As shown in the above code block, when the component loads a fetch request is made to the dog API, which ultimately resolves to a response object that is parsed as JSON and finally stored in the images state by calling setImages. This state is then used in the returned JSX which will be displayed to the user. From the user perspective, all the individual will see is a dog image displayed when they first load the webpage. &lt;/p&gt;

&lt;p&gt;However, the way useEffect is currently written above, it will eventually result in an error. The reason being that we did not pass in a second argument called a dependency array. A dependency array allows us to control when useEffect gets called. In the above example, because we did not pass in a dependency array, useEffect will be called continuously which will result in an endless loop of fetch requests. This will eventually lead to the API kicking us out for hitting the rate limit. &lt;/p&gt;

&lt;p&gt;A solution to this is passing in an empty dependency array like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect } from "react";

function DogPics() {
  const [images, setImages] = useState([]);

  useEffect(() =&amp;gt; {
    fetch("https://dog.ceo/api/breeds/image/random/3")
      .then((r) =&amp;gt; r.json())
      .then((data) =&amp;gt; {
        // setting state in the useEffect callback
        setImages(data.message);
      });
  }, [] ); // added empty dependency array

  return (
    &amp;lt;div&amp;gt;
      {images.map((image) =&amp;gt; (
        &amp;lt;img src={image} key={image} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By including an empty dependency array as a second argument to useEffect, useEffect will only be called when the component first mounts. This will prevent an endless loop of fetch requests and will only fetch the data once when the component first loads. &lt;/p&gt;

&lt;p&gt;Another way to control when useEffect gets called is passing in a state into the dependency array like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect } from "react";

function DogPics() {
  const [images, setImages] = useState([]);

  useEffect(() =&amp;gt; {
    fetch("https://dog.ceo/api/breeds/image/random/3")
      .then((r) =&amp;gt; r.json())
      .then((data) =&amp;gt; {
        // setting state in the useEffect callback
        setImages(data.message);
      });
  }, [images] ); // added images state dependency array

  return (
    &amp;lt;div&amp;gt;
      {images.map((image) =&amp;gt; (
        &amp;lt;img src={image} key={image} /&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
}
Note: Although adding the images state in the dependency array in this context does not logically make sense, this is purely for demonstration purposes.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the same block of code we've been using, we've now passed in the images state to the dependency array. So now useEffect will be called when the component first mounts and will subsequently be called again if the state in the dependency array updates. So in our case after useEffect is called when the component first mounts, it will be called again if the images state is ever updated. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Fetching data from an API when a website first loads and storing it in some type of variable are basic concepts that all new developers should be familiar with. Both the State and Effect Hook help simplify this process which shows the effectiveness and efficiency of React hooks. As developers we will come across many other hooks that will assist us in our React development but should keep in mind of two general rules that should be followed when it comes to React hooks. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Only call Hooks at the tope level.&lt;/li&gt;
&lt;li&gt;Only call Hooks from React function components.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For more information on hooks or React in general you can always refer to their documentation on their website.&lt;/p&gt;

&lt;p&gt;Good Luck!&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://reactjs.org/docs/hooks-overview.html"&gt;https://reactjs.org/docs/hooks-overview.html&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>react</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Removing Duplicate Objects from an Array</title>
      <dc:creator>KevinZ-CS</dc:creator>
      <pubDate>Fri, 15 Jul 2022 23:37:12 +0000</pubDate>
      <link>https://dev.to/kevinzcs/removing-duplicate-objects-from-an-array-pdl</link>
      <guid>https://dev.to/kevinzcs/removing-duplicate-objects-from-an-array-pdl</guid>
      <description>&lt;p&gt;One of the most common data structure that web developers encounter is an array of objects. Many times the data provided are not formatted or structured to accommodate for the needs of the user. As developers we will typically be required to manipulate the data so that it's tailor fit for our own use case. In this blog I will be discussing a creative solution that I came across online that is used to remove duplicate objects in an array.  &lt;/p&gt;

&lt;p&gt;To start off, let's say we have a given data structure shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const students = [
  {id: 12, fName: 'John', lName: 'Smith'},
  {id: 75, fName: 'Anthony', lName: 'Smith'},
  {id: 100, fName: 'Mary', lName: 'Jane'},
  {id: 12, fName: 'Jane', lName: 'Doe'},
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this data structure the id with the value of 12 is repeated twice. What if we only want to show 1 object with an id of 12 in that array? This can be accomplished by using a combination of common Javascript methods which includes: &lt;strong&gt;reduce&lt;/strong&gt;, &lt;strong&gt;set&lt;/strong&gt;, &lt;strong&gt;values&lt;/strong&gt;, and the &lt;strong&gt;spread operator&lt;/strong&gt;.&lt;br&gt;
In order to understand how these methods can be used in combination with one another it is advised that you have have a basic understanding of each method which are covered below. If you are already familiar with these methods you can skip to the &lt;strong&gt;Solution&lt;/strong&gt; section. &lt;/p&gt;
&lt;h2&gt;
  
  
  Reduce
&lt;/h2&gt;

&lt;p&gt;The reduce method is used on an array and reduces it to a single value. An example of the syntax for this method is shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1,2]
array.reduce(function(accumulator, currentValue){return accumulator + current value}
, initialValue)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As shown above, the reduce function takes in 2 parameters with one being the callback function that is going to be called on each element of the array as it iterates through and the second parameter being the initial value(the value that will be assigned to accumulator on the first iteration). As the callback is being called on each iteration the result of the callback will be stored in the accumulator value which will then be used in the subsequent iteration until every element in the array has been iterated through&lt;/p&gt;

&lt;p&gt;For this example, if we set the initial value to 10, on the first iteration using 1 as the current value the callback function will return 11. So accumulator = 10 + currentValue = 1 will return 11. On the next iteration 11 will be stored in the accumulator parameter and currentValue will be 2 and the callback will return 13 since 11 + 2 = 13. &lt;/p&gt;

&lt;p&gt;In summary, we started off with an array with 2 values and given a starting value of 10 the reduce method returned a single value of 13. In addition, keep in the mind that when using reduce, &lt;strong&gt;single value does not mean that it has to be a single number, it can also be a single object(more on this later)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Set
&lt;/h2&gt;

&lt;p&gt;When this method is called on a map object it will populate the object with a unique key value pair. If the map object already contains a key that you're trying to add it will override that key value pair with the current key value pair to prevent any duplicate keys. Below is an example of adding key value pairs to an empty map using set.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const map1 = new Map();

map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
map1.set('a', 3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice how in the above example that I tried to add a duplicate key value of &lt;em&gt;a:3&lt;/em&gt;. Since this was the last key value pair added to the object and the key &lt;em&gt;a&lt;/em&gt; already exists in the map object, if I were to console.log(map1) key &lt;em&gt;a&lt;/em&gt; will only show up once and the value for the key  will be 3 since set overrides any duplicate keys. &lt;/p&gt;

&lt;h2&gt;
  
  
  Values
&lt;/h2&gt;

&lt;p&gt;When the values method gets called on an object it will return an array with just the values. See below for an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Spread Operator
&lt;/h2&gt;

&lt;p&gt;The spread operator allows us to copy an existing array into another array or object. See below example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;Now that we have a basic understanding of these 4 methods we can now dive into the solution of our original problem which was to remove duplicate objects within an array. Recall that our students array is as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const students = [
  {id: 12, fName: 'John', lName: 'Smith'},
  {id: 75, fName: 'Anthony', lName: 'Smith'},
  {id: 100, fName: 'Mary', lName: 'Jane'},
  {id: 12, fName: 'Jane', lName: 'Doe'},
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the reduce method on the above array we can write:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const uniqStudents = students.reduce((map, obj) =&amp;gt; {_code goes here_}, newMap());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we are calling the reduce method on the students array and passing 2 parameters into reduce. The first parameter is the callback function that is taking in another 2 parameters, map and obj with map being the accumulator value and obj being the current value. The second parameter that is being passed into reduce is the initial accumulator in this case is newMap() an empty map object.&lt;/p&gt;

&lt;p&gt;Now let's add in the code inside the callback function brackets.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const uniqStudents = students.reduce((map, obj) =&amp;gt; {return map.set(obj.id, obj)}, new Map());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's unpack what is happening here. &lt;/p&gt;

&lt;p&gt;The reduce method is iterating through each object in the initial students array given the initial accumulator value being an empty object. &lt;/p&gt;

&lt;p&gt;On the first iteration we are adding a new object to the empty map object using .set and specifying that the key for the object being added is obj.id and value being the entire original object. &lt;/p&gt;

&lt;p&gt;Once reduce iterates through every object in the original, the empty map object will now contain:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3vrlvl2Z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8bb3fgfo7puahmljjg7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3vrlvl2Z--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8bb3fgfo7puahmljjg7.png" alt="Image description" width="736" height="255"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Notice how the key for id:12 only shows up once now. This because we used the .set method which overrides any duplicate keys with the latest key value pair. Now that we've got rid of the objects with duplicate Ids the last thing to do is to grab the values of each object and put them into a new array using the .values() and the spread operator. The code will look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const uniqStudents = [...students.reduce((map, obj) =&amp;gt; {return map.set(obj.id, obj)}, new Map()).values();]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the result looking like this if we console.log(uniqStudents):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WDYOMZUS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/285js3jssyf3b17inrqu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WDYOMZUS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/285js3jssyf3b17inrqu.png" alt="Image description" width="737" height="120"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In summary, we were able to reduce an array of objects into a single value(in this case is a single object with other objects nested within) and used the set method to remove any objects with duplicate keys that are nested in that single object. After removing the objects with duplicate keys we then use the values method to grab the values of each object and place it into a new array using the spread operator. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Just from this one scenario of removing duplicates we've utilized a bunch of common Javascript methods which really goes to show the power of basic Javascript functions when used in combination with one another! What are some other ways to remove duplicate objects in an array? Let's discuss!&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources:
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map&lt;/a&gt;&lt;br&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.w3schools.com/react/react_es6_spread.asp"&gt;https://www.w3schools.com/react/react_es6_spread.asp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.youtube.com/watch?v=5JFJTGZ4gHQ"&gt;https://www.youtube.com/watch?v=5JFJTGZ4gHQ&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
