<?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: masonbarnes645</title>
    <description>The latest articles on DEV Community by masonbarnes645 (@masonbarnes645).</description>
    <link>https://dev.to/masonbarnes645</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%2F1557171%2Fbb1c4fae-af56-4309-b362-c648d87b9451.png</url>
      <title>DEV Community: masonbarnes645</title>
      <link>https://dev.to/masonbarnes645</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/masonbarnes645"/>
    <language>en</language>
    <item>
      <title>Utilizing OAuth 2.0 with Google</title>
      <dc:creator>masonbarnes645</dc:creator>
      <pubDate>Thu, 12 Sep 2024 16:30:42 +0000</pubDate>
      <link>https://dev.to/masonbarnes645/utilizing-oauth-20-with-google-59p3</link>
      <guid>https://dev.to/masonbarnes645/utilizing-oauth-20-with-google-59p3</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In today’s world of apps and websites, offering users a secure and frictionless login experience is essential. Google OAuth 2.0 is one of the most popular ways to integrate login functionality into your application. It allows users to sign in using their Google accounts, simplifying the process while ensuring high security standards. In this post, we’ll walk through the basics of setting up Google OAuth 2.0.&lt;/p&gt;

&lt;p&gt;What is OAuth 2.0?&lt;br&gt;
OAuth 2.0 is an open-standard authorization framework that allows third-party apps to access user data without exposing their login credentials. It grants apps limited access to a user’s data via tokens rather than passwords. OAuth is widely adopted for authentication and authorization flows, particularly for social logins like Google, Facebook, and GitHub.&lt;/p&gt;

&lt;p&gt;Why Use Google OAuth 2.0?&lt;/p&gt;

&lt;p&gt;Security: OAuth ensures user credentials stay protected, using tokens instead of passwords.&lt;/p&gt;

&lt;p&gt;Ease of Use: Users can sign in with their existing Google account, eliminating the need for a separate username and password.&lt;/p&gt;

&lt;p&gt;User Trust: Google’s brand recognition helps build user confidence in your app’s login process. By streamlining user authentication, you reduce signup friction and improve the overall user experience.&lt;/p&gt;
&lt;h2&gt;
  
  
  How to Implement Google OAuth 2.0
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F32peo5qdakluxksyco92.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F32peo5qdakluxksyco92.png" alt="Image description" width="382" height="280"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 1: Create a Project in Google Cloud Console&lt;br&gt;
To start, go to the Google Cloud Console. Create a new project or select an existing one. Once your project is set up, navigate to the “API &amp;amp; Services” section and enable the Google OAuth 2.0 API. This allows your application to use Google’s authentication services.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8nmmo0hfnxockwkg52nr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8nmmo0hfnxockwkg52nr.png" alt="Image description" width="589" height="210"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 2: Set Up OAuth Credentials&lt;br&gt;
In the Google Cloud Console, go to the “Credentials” tab and click “Create Credentials.” Select “OAuth 2.0 Client IDs” and follow the prompts to configure the OAuth consent screen. This is what your users will see when signing in with Google. Here, you’ll need to specify your app’s name, domain, and privacy policy URL.&lt;/p&gt;

&lt;p&gt;Once the consent screen is configured, create the OAuth 2.0 credentials. Specify your app's redirect URI (the URL where users will be redirected after Google signs them in) and keep your Client ID and Client Secret handy for the next step.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhofdj64nrbqmxkya7snc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhofdj64nrbqmxkya7snc.png" alt="Image description" width="697" height="790"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 3: Integrate Google OAuth with Your App&lt;br&gt;
Now that you have the credentials, it’s time to integrate Google OAuth into your app. Depending on what frameworks you are using, there are different libraries and tools to make this process easier:&lt;/p&gt;

&lt;p&gt;Frontend (React): Use the react-google-login package, which allows you to easily trigger the Google login and retrieve user information.&lt;br&gt;
Backend (Flask): Use the google-auth-library to verify tokens and manage sessions. The backend will handle verifying the ID token received from the client to ensure the user’s identity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  useEffect(() =&amp;gt; {
    google.accounts.id.initialize({
      client_id: 
        "149675200689-v4e6n63l8uf098kemu3mss77kgi6qhp4.apps.googleusercontent.com",
      callback: handleCallbackResponse
    })
    google.accounts.id.renderButton(
      document.getElementById("Oauth-div"),
      { theme:"outline", size: "large"}
    )

  },[])

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

&lt;/div&gt;



&lt;p&gt;Once integrated, users will be able to sign in using their Google accounts, and you can securely manage authentication in your app.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzx9uzrhabdo4z0teahzi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzx9uzrhabdo4z0teahzi.png" alt="Image description" width="517" height="319"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Key Security Considerations
When implementing OAuth 2.0, it’s essential to follow some key security practices:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Secure Client Secrets: Never expose your Client Secret in your frontend code. Keep it on the server-side to avoid leaking it to users.&lt;br&gt;
Use HTTPS: Always use HTTPS for redirect URIs. This ensures tokens and user data are encrypted in transit.&lt;br&gt;
Validate ID Tokens: On the backend, validate the ID tokens received from Google to confirm their authenticity. This prevents token tampering and ensures secure authentication.&lt;/p&gt;

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

&lt;p&gt;Google OAuth 2.0 makes it easy to implement a secure and trusted login system for your app. By following the steps above, you can offer users a smooth and familiar authentication process while keeping their credentials safe. Ready to dive deeper? Explore Google’s full OAuth 2.0 documentation to learn about advanced flows, token expiration management, and handling different user scopes.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Webscraping Using Python</title>
      <dc:creator>masonbarnes645</dc:creator>
      <pubDate>Wed, 14 Aug 2024 23:48:38 +0000</pubDate>
      <link>https://dev.to/masonbarnes645/web-scraping-using-python-1jbl</link>
      <guid>https://dev.to/masonbarnes645/web-scraping-using-python-1jbl</guid>
      <description>&lt;h2&gt;
  
  
  Basics of webscraping
&lt;/h2&gt;

&lt;p&gt;Webscraping is a powerful tool that allows you to access valuable data from website without using an API. Some websites contain information in their HTML, but do not have an API that you can use. If you wanted data from one of these websites, you could utilize webscraping. Webscraping goes through the HTML of a website, and lets you extract the data you want by parsing through the HTML. Packages like BeautifulSoup, requests, and Scrapy are used to help in this process. In this post, I will explore the basics of using BeautifulSoup to get data from a website.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why utilize web scraping?
&lt;/h2&gt;

&lt;p&gt;There are many use cases where web scraping would make achieving your desired function easier and more efficiently. For example, a company might utilize webscraping to do market research, by going through websites, and extracting, prices, reviews, and product detail. To gather the same data manually would obviously be a much more laborious and slower process. Another usecase for webscraping is to aggregate content from multiple websites without the need for manual entry. The uses for webscraping extend far beyond these examples, and makes it an essential tool in data collection.&lt;/p&gt;

&lt;h2&gt;
  
  
  Web scraping example
&lt;/h2&gt;

&lt;p&gt;Here is a very simple example showing how you can use BeautifulSoup to scrape through a website and extract information.&lt;br&gt;
After you install and import all of the necessary packages, retrieve the HTML from your website and use BeautifulSoup to parse the HTML:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;html = requests.get("https://information.com/", headers=headers)

doc = BeautifulSoup(html.text, 'html.parser')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This gives you a doc variable that we can filter unneeded information from, leaving us with only the parts we are looking for. The are a couple BeautifulSoup method we'll use to further filter and simplify the HTML.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(doc.select('.heading')[0].contents)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this line of code we select all elements that match the targeted CSS selector(e.g. class, id, etc.)'heading' by using the .select()  method. Then, we take the first element of that class by using [0], and extract its text by getting the attribute 'contents'. Contents can only be used  on a single element, so an error would be raised if you tried to use it on multiple elements. You can also use the get_text() method which will return the information you want.&lt;br&gt;
Of course there would be many further steps in order to filter, manipulate and analyze the data you scraped, but for simplicity's sake, I will leave the function as printing the text information from the element.&lt;/p&gt;

&lt;h2&gt;
  
  
  Storing and using scraped data
&lt;/h2&gt;

&lt;p&gt;There are many useful libraries that allow you to meaningfully interact with, or store the data you scraped from the web. After you have scraped through a website, you can store the gathered data in sql databases for structured access to all of your data. After you have inserted the data into your table, there are more packages that allow you to visualize or interact with the data. For example 'pandas' is a versatile library that allows you to explore, visualize and manipulate the data you have stored. Using pandas, you can analyze data using functions that calculate mean, median, etc. as well as correlations within the data. You can also visualize the data using plots, graphs, etc. because pandas integrates with Matplotlib, another python library. You can use pandas to 'clean' your data, helping patch up any missing values, duplicates, and unnecessary information. In terms of manipulating using pandas, it provides functions that allow you merge databases, allowing you to consolidate different pieces of information into one table. As you can see, there are many tools that you can use to get the most from the information you scraped.&lt;br&gt;
I look forward to utilizing webscraping in more complex ways in the future, and I hope I have convinced you of its immense value!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Creating and Managing Databases with SQLite and Python</title>
      <dc:creator>masonbarnes645</dc:creator>
      <pubDate>Wed, 31 Jul 2024 00:34:13 +0000</pubDate>
      <link>https://dev.to/masonbarnes645/creating-and-managing-databases-with-sqlite-and-python-2aap</link>
      <guid>https://dev.to/masonbarnes645/creating-and-managing-databases-with-sqlite-and-python-2aap</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;During phase 3 as a Flatiron student, I was introduced to python as well as SQL. Though it has been overwhelming at times, I wanted to share what I have learned about database management during that process. In this blog post, I'll cover how to set up databases, manage relationships between databases, perform CRUD actions, and how to design a schema for your database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up Database with SQLite
&lt;/h2&gt;

&lt;p&gt;The first step is of course to make sure we have the right tools to work with SQLite. Because it is already contained in the standard Python library, no installation is required, only import. Here is what that would look like:&lt;br&gt;
&lt;code&gt;import sqlite3&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once we know we have SQLite, we can take our first steps in creating a workable database. First, we need to enter two lines of code that are essential in creating and interacting with the data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CONN = sqlite3.connect('database.db')
CURSOR = CONN.cursor()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets take a look at this code line by line. The first line allows us to connect to a SQL database, and it will create a file if one does not exist. This is our door to interacting with the data.&lt;br&gt;
The second line creates a cursor object which is essential for executing commands and queries in SQLite. The cursor object is responsible for executing CRUD commands that are used to add, delete, update, and find information within the table. We also use the cursor object to execute queries and fetch information. In those cases, we use CURSOR.fetchone() or CURSOR.fetchall() to retrieve results from the database.&lt;/p&gt;
&lt;h2&gt;
  
  
  Designing Schema for Data
&lt;/h2&gt;

&lt;p&gt;Schemas are absolutely needed for creating uniform tables with all the desired information. A schema is essentially a template that you create, showing how you want the table to be set up. The schema defines what columns you want in your table, which will represent each different category of information you want to store. In addition, it will specify the data type you want the table to store in those columns. Common data types include TEXT, INTEGER(whole numbers), and REAL(floating-point numbers). Let's see 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;    @classmethod
    def create_table(cls):
        try:
            CURSOR.execute(
                """
                CREATE TABLE IF NOT EXISTS customers (
                    id INTEGER PRIMARY KEY,
                    name TEXT,
                    age INTEGER,
                    company TEXT,
                    email TEXT UNIQUE
                );
                """
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we use the cursor objects to create a table with 5 columns. The first column is the primary key, which allows each row to have a unique number to be found with. The other columns are name, age company, and email. Name, company, and email are all followed by TEXT, meaning they expect a string when a new row is created. Age on the other hand, is followed by INTEGER, meaning a number will be accepted for each row. It is also worth noting the use of the UNIQUE keyword, which forces uniqueness for every row among the email column.&lt;/p&gt;

&lt;h2&gt;
  
  
  CRUD Operations in SQLite
&lt;/h2&gt;

&lt;p&gt;CRUD operations are the primary way to populate databases, update information when needed, retrieve information, and delete data from the database. CRUD is an acronym for create, read, update, delete. SQLite has its own keywords that are used to perform these essential functions.&lt;/p&gt;

&lt;p&gt;The first keyword we will discuss is INSERT INTO, which allows us to add new rows to an existing table:&lt;br&gt;
&lt;code&gt;cursor.execute('INSERT INTO Users (name, email) VALUES (?, ?)', ('Mason', 'Mason@example.com'))&lt;/code&gt;&lt;br&gt;
Here you can see that we added a new row into our table with name and email values.&lt;/p&gt;

&lt;p&gt;The keyword that allows us to "read" information is SELECT. SELECT is flexible and allows us to pick and choose which rows we want by using WHERE, for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @classmethod
    def find_by_id(cls, id):
        CURSOR.execute(
            """
          SELECT * FROM customers
          WHERE id == ?
            """, (id,)
        )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we select the whole row using *, but only the row that matches the id given.&lt;/p&gt;

&lt;p&gt;To update tables in SQLite, we use the keyword UPDATE. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; UPDATE students SET grade = 100 WHERE name = “Mason”;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we can make use of WHERE once again to selectively update only the rows we want to.&lt;/p&gt;

&lt;p&gt;Finally, we come to the delete part of CRUD. Delete is pretty simple, and intuitively uses the keyword DELETE. Lets take a look at 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;cursor.execute('DELETE FROM customers WHERE name = ?', ('Mason',))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here we use the delete method to remove the row with the name 'Mason' from the data table.&lt;/p&gt;

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

&lt;p&gt;In this post, we took a look at the basic, but important aspects of working with SQLite and Python, seeing how to create and manage databases effectively. While there is much much more to know about SQL and Python, these tools will allow you to create your own data tables and interact with them how you wish!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Using useRef(), useState()</title>
      <dc:creator>masonbarnes645</dc:creator>
      <pubDate>Sun, 07 Jul 2024 22:55:11 +0000</pubDate>
      <link>https://dev.to/masonbarnes645/using-useref-usestate-useeffect-4kmi</link>
      <guid>https://dev.to/masonbarnes645/using-useref-usestate-useeffect-4kmi</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;Two very important hooks in React are useState() and useRef(). While used in similar ways, they have unique use cases in which each one is better equipped to solve a problem. In this post, I'll go over useState and useRef, and go over some common use cases for each.&lt;/p&gt;

&lt;h2&gt;
  
  
  Render Cycle explanation
&lt;/h2&gt;

&lt;p&gt;Before getting into useState() and useRef(), it's important to understand the React render cycle. When a state in a React component changes, the component re-renders to reflect this change in the UI. This re-rendering is a crucial aspect of React’s declarative approach, ensuring that the UI is always in sync with the current state of the application. However, not all changes require a re-render, which is where useRef comes in handy.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7db02oyyn1ywmwwq77pf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7db02oyyn1ywmwwq77pf.png" alt="Image description" width="800" height="278"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  useState explanation
&lt;/h2&gt;

&lt;p&gt;useState() is a commonly used hook in React, and is necessary in adding functionality to many different features. useState() allows you to add a &lt;em&gt;state variable&lt;/em&gt; to your component. Before we go over some of the uses for  useState() lets look at how to implement it in your code. The first thing we need to do is import useState().&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;Now that useState() is imported, we can call useState at the top level of our component to declare a state variable. Using array destructuring, we declare both a state variable, as well as a set function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [number, setNumber] = useState(0)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, number is our state variable, and setNumber is our set function. That means we can use setNumber to update the &lt;em&gt;state&lt;/em&gt; of number, and trigger a re-render of our componenet( this is important ). You may have also noticed a 0 after useState. That is the initial value, meaning that will be the value of the number state initially. It is important to note that if you want to update the state correctly, you need to use the set function. You cannot modify the variable directly. State is also immutable, meaning in cannot be changed. This may seem impossible considering how we use state, but within the context of one render, state is immutable. It can only change in between renderings. That is a basic rundown of useState() and its functionality, useRef() is similar, but different in a very important way.&lt;/p&gt;

&lt;h2&gt;
  
  
  useRef explanation
&lt;/h2&gt;

&lt;p&gt;useRef() is declared in a similar way to useState(), it accepts an initial  value that you can change depending on what you need for your program.&lt;br&gt;
&lt;/p&gt;

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

function MyComponent() {
    const reference = useRef(null);

}

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

&lt;/div&gt;



&lt;p&gt;Unlike useState(), useRef() does not trigger a re-render. This makes useRef() ideal for keeping 'references' to values that do not need a re-render when they are changed.&lt;/p&gt;

&lt;h2&gt;
  
  
  useState Use Cases
&lt;/h2&gt;

&lt;p&gt;An example of a frequent use for useState() would be handling a light/dark &lt;br&gt;
mode for a webpage&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = () =&amp;gt; setDarkMode(!darkMode);

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

&lt;/div&gt;



&lt;p&gt;In this example, we can dynamically render the page based on the state "darkMode". &lt;/p&gt;

&lt;p&gt;Another use of useState() is the handling of forms. We can use state to hand user input dynamically, updating state when the user types something.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [name, setName] = useState('');
const handleInputChange = (e) =&amp;gt; setName(e.target.value);

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

&lt;/div&gt;



&lt;p&gt;As you can see, we change the value of the 'name' state whenever the user inputs something into the form.&lt;/p&gt;

&lt;h2&gt;
  
  
  useRef Use Cases
&lt;/h2&gt;

&lt;p&gt;useRef() is useful when we need to change values without re-rendering the component. In this example use case, we want to store a mutable value. We can increment the value without re-rendering the component&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const countRef = useRef(0);
const incrementRef = () =&amp;gt; countRef.current++;

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

&lt;/div&gt;



&lt;p&gt;It is also used in dynamic UI updates. useRef plays an important role in updating the UI dynamically. Storing reference to DOM elements or other mutable values allows components to update parts of the UI based on changing data or user inputs, without causing re renders.&lt;/p&gt;

&lt;p&gt;Another valuable use of useRef is synchronizing with external libraries. By using a reference you assure that the UI is always using the most recent value it can display.&lt;/p&gt;

&lt;p&gt;Overall, useRef is a valuable tool that maintains the freshest data, optimizing performance and enabling flexible updates in React applications.&lt;/p&gt;

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

&lt;p&gt;useState() and useRef() are powerful tools in React with unique purposes. useState is essential for managing state that impacts rendering, while useRef is for persisting values across renders without causing a re-render. Understanding how to use these hooks, and when to use them, will allow you to create dynamic webpages&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Iterating Data Structures in JavaScript</title>
      <dc:creator>masonbarnes645</dc:creator>
      <pubDate>Sat, 15 Jun 2024 20:32:50 +0000</pubDate>
      <link>https://dev.to/masonbarnes645/iterating-data-structures-in-javascript-o26</link>
      <guid>https://dev.to/masonbarnes645/iterating-data-structures-in-javascript-o26</guid>
      <description>&lt;h2&gt;
  
  
  Data Structures
&lt;/h2&gt;

&lt;p&gt;Data structures in JavaScript are the backbone of functionality for most of the projects that I have made in my short coding journey. Data structures, like objects and arrays contain the information that programs need to access for a multitude of reasons. If we have a lot of information or data, these data structures will be the best way to store that information.&lt;/p&gt;

&lt;p&gt;Of course, at some point, we will want to access this information. While it is possible to retrieve each element one by one, this is obviously not a feasible way to build code. Ideally, we would want to build one piece of code that helps us sort through the entire array or object. Luckily, we do! We can build a chunk of code using an iterator, allowing us to repeatedly fire code on the information we need to. In this post, I'll go over how we can use iterators, and some useful scenarios to employ them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Methods Used For Iteration
&lt;/h2&gt;

&lt;p&gt;There are many different methods we can use to iterate objects and arrays in JavaScript. Most of these methods will be used on arrays. I won't go over every single method, but I would like to highlight some important ones that serve to showcase iteration as a whole.&lt;/p&gt;

&lt;p&gt;I would like to talk about a couple different types of iterators in this blog, the first type being iterators that allow you to search for existing elements within your array.&lt;/p&gt;

&lt;h2&gt;
  
  
  Search Iterators
&lt;/h2&gt;

&lt;p&gt;As the name suggests, search iterators are used to iterate over arrays and return specific values. There are many different methods that belong to this category, that can be used in many different ways. I'll start with a very basic example to show what I mean. Here is an example of the find() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const prices = [9, 19, 49, 99,]

function searchPrices(price){
  if ( price &amp;gt; 40){
    return price
  } 
}


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

&lt;/div&gt;



&lt;p&gt;In this example, we would use the find method 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;prices.find(searchPrices)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We place our array first, then the find method, and finally we pass the callback function searchTeams as the argument. The find method will go through every element in the array, and run the searchPrces function on it. When it finally finds a price over 40, it returns that price, 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;'49'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The find method is very limited, because it only returns the first matching element it finds, but it is a good example of all search iterators. If no price matching the criteria is found, find will return undefined.&lt;/p&gt;

&lt;p&gt;Instead of just one element, maybe you want a whole list of matching elements. This too is possible with array iterators, using the filter method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const teams = ['76ers', 'thunder', 'timberwolves', 'heat','warriors']

function searchTeams(team){
  if (team.includes('s'))
    return team
}

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

&lt;/div&gt;



&lt;p&gt;Using the same notation, replacing find with filter, 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;teams.filter(searchTeams)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;which returns:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ '76ers', 'timberwolves', 'warriors' ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;as you can see, the filter method returns all the teams that contain the letter 's', packaged in an array. It's worth making a note that if there are no matching values, instead of an undefined value, it will return an empty array. I'm sure that you can imagine many uses this method could have in retrieving data, that is the power of iterators.&lt;/p&gt;

&lt;h2&gt;
  
  
  Other Iterators
&lt;/h2&gt;

&lt;p&gt;It's hard for me to come up with a name that incapsulates non-search array iterators, because their uses are vast and unique. The most basic, but still very useful iterator is forEach. It has a somewhat intuitive name, and you might have guessed that for each array element, it calls a function. Lets take a look at 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 teams = ['yankees', 'mets', 'mariners']

function changeTeams(team){
   let result = team.toUpperCase()

   console.log(result)


}

teams.forEach(changeTeams)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you may have already guess, the result is that the console logs the follwing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;YANKEES
METS
MARINERS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So as you can see, the forEach did exactly what is what meant to do. It went to each element in the array, and ran the changeTeams function, making them uppercase.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using Iteration for Non-Array Objects
&lt;/h2&gt;

&lt;p&gt;One way to utilize iteration on non-array objects is to convert part of the object into an iterable array. While you cannot use methods I've outlines to iterate over non-array objects, you can use them after you convert into an array.&lt;br&gt;
The way you would accomplish this is by using the Object.keys() or Object.values() method. After using one of those two methods, you can iterate the array that is returned.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const car = {
  make: "Toyota",
  model: "Prius",
  year: 2008,
};

typeOfCar = Object.values(car)
console.log(typeOfCar)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we use Object.values() to get an array of information from the object car. When typeOfCar is logged, it will look 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;[ 'Toyota', 'Prius', 2008 ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have this array, we can use any iterators we want on it. The same methodology will work using Object.keys(). This allows us to utilize iteration methods on non-array objects.&lt;/p&gt;

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

&lt;p&gt;Iterators are some of the most important and useful methods. Whether you are searching for elements, want to change an array, return a modified copy of an array, or reduce an array to a single value, there is an iterator that will do it for you. What I've shown in this short blog is only one very small glimpse into the power of iterating data structures, and I encourage anyone to explore them as much as possible.&lt;/p&gt;

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

&lt;p&gt;&lt;a href="https://www.w3schools.com/jsref/jsref_find.asp"&gt;https://www.w3schools.com/jsref/jsref_find.asp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.w3schools.com/jsref/jsref_filter.asp"&gt;https://www.w3schools.com/jsref/jsref_filter.asp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.w3schools.com/jsref/jsref_object_values.asp"&gt;https://www.w3schools.com/jsref/jsref_object_values.asp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.w3schools.com/jsref/jsref_object_keys.asp"&gt;https://www.w3schools.com/jsref/jsref_object_keys.asp&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.w3schools.com/jsref/jsref_foreach.asp"&gt;https://www.w3schools.com/jsref/jsref_foreach.asp&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
