<?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: Steph</title>
    <description>The latest articles on DEV Community by Steph (@stephbert).</description>
    <link>https://dev.to/stephbert</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%2F1275748%2F5a5e55e6-0671-470d-ad8e-d540522d8401.png</url>
      <title>DEV Community: Steph</title>
      <link>https://dev.to/stephbert</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/stephbert"/>
    <language>en</language>
    <item>
      <title>An Introduction to Bubble Sort</title>
      <dc:creator>Steph</dc:creator>
      <pubDate>Tue, 07 May 2024 04:48:12 +0000</pubDate>
      <link>https://dev.to/stephbert/an-introduction-to-bubble-sort-288o</link>
      <guid>https://dev.to/stephbert/an-introduction-to-bubble-sort-288o</guid>
      <description>&lt;p&gt;&lt;strong&gt;What are Sorting Algorithms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Sorting algorithms are used to rearrange elements in a collection (such as an array or a list) into a particular order. For example, taking an input of [2, 3, 1, 4] and sorting it in ascending order: [1, 2, 3, 4]. In programming there are many different sorting algorithms. We’re going to explore the most basic, Bubble Sort, in this blog post, but here’s a quick overview of other common sorting algorithms, along with links where you can learn more about them:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.geeksforgeeks.org/selection-sort/" rel="noopener noreferrer"&gt;Selection Sort&lt;/a&gt;: Finds the smallest (or largest, depending on the sorting order) element in the unsorted portion of the list and swaps it with the first unsorted element.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.geeksforgeeks.org/insertion-sort/" rel="noopener noreferrer"&gt;Insertion Sort&lt;/a&gt;: Builds the sorted portion of the list one element at a time by repeatedly taking the next element from the unsorted portion and inserting it into its correct position in the sorted portion.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.geeksforgeeks.org/merge-sort/" rel="noopener noreferrer"&gt;Merge Sort&lt;/a&gt;: Divides the list into smaller sublists, recursively sorts each sublist, and then merges them back together.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.geeksforgeeks.org/quick-sort/" rel="noopener noreferrer"&gt;QuickSort&lt;/a&gt;: Selects a pivot element from the list and partitions the other elements into two sublists according to whether they are less than or greater than the pivot.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;What is Bubble Sort&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Bubble Sort is a simple sorting algorithm that starts at the beginning of a list and compares each pair of adjacent elements. If the elements are in the wrong order (i.e., the element on the left is greater than the element on the right if you're sorting in ascending order), the elements are swapped. This process is repeated for each pair of adjacent elements in the list.&lt;/p&gt;

&lt;p&gt;Eg. Bubble Sort in Ascending Order: &lt;/p&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%2Ff52owwp4jb4mbbnrz4w7.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%2Ff52owwp4jb4mbbnrz4w7.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code Examples&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s dive into how you would set up an iterative Bubble Sort in Python:&lt;/p&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%2Fr01bejxtfc8b33l9nfzm.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%2Fr01bejxtfc8b33l9nfzm.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The outer loop (&lt;strong&gt;for i in range(n)&lt;/strong&gt;) loops through the array from 0 to n-1. N is the length of the array. The inner loop (&lt;strong&gt;for j in range(0, n-i-1)&lt;/strong&gt;) starts another loop that iterates from 0 to n-i-2. This loop performs the comparison and swaps elements with each pass through the array. Since the array’s index starts at zero, we subtract 1 from n, and n-i-1 ensures that the algorithm doesn't compare already sorted elements in subsequent passes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;if arr[j] &amp;gt; arr[j+1]:&lt;/strong&gt; checks if the current element (arr[j]) is greater than the next element (arr[j+1]). If it is, it means they are in the wrong order and need to be swapped. &lt;strong&gt;arr[j], arr[j+1] = arr[j+1], arr[j]&lt;/strong&gt; swaps the current element (arr[j]) with the next element (arr[j+1]). This sorts the adjacent elements in the array.&lt;/p&gt;

&lt;p&gt;For reference, here’s the same code in JavaScript:&lt;/p&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%2Fkh5554dy9mvjz8bc5anf.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%2Fkh5554dy9mvjz8bc5anf.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Big O Analysis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Time Complexity: O(N^2)&lt;/p&gt;

&lt;p&gt;The time complexity of a Bubble sort algorithm is O(N^2), where N represents the number of elements in the array. In the worst-case scenario, the algorithm would need to perform comparisons and swaps with every other element in the array, so it would need to run through N elements. Since we have a nested loop, we take the time complexity of the outer loop (0(N)) and multiply it by the time complexity of the inner loop (O(N)) to arrive at O(N^2).&lt;/p&gt;

&lt;p&gt;Space Complexity: O(1)&lt;/p&gt;

&lt;p&gt;Bubble Sort is an &lt;strong&gt;in-place sorting algorithm&lt;/strong&gt; because it doesn't require any extra space proportional to the size of the input array. Its space complexity is O(1) since the space used by the algorithm is constant regardless of the size of the input array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages &amp;amp; Disadvantages&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some of the advantages of Bubble Sort compared to other sorting algorithms is that it is easy to understand and to set up, and it doesn’t require any additional memory space. Since Bubble Sort algorithms have a relatively high time complexity of O(N^2), one of their disadvantages is that they can be slow for large data sets.&lt;/p&gt;

&lt;p&gt;Sources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Flatiron School Curriculum, Data Structures &amp;amp; Algorithms, Days 1-2: Bubble Sort&lt;/li&gt;
&lt;li&gt;GeeksForGeeks, &lt;a href="https://www.geeksforgeeks.org/bubble-sort/" rel="noopener noreferrer"&gt;Bubble Sort – Data Structure and Algorithm Tutorials&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;W3Schools, &lt;a href="https://www.w3schools.com/dsa/dsa_algo_bubblesort.php" rel="noopener noreferrer"&gt;DSA Bubble Sort&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;YouTube, Telusko, &lt;a href="https://www.youtube.com/watch?v=Vca808JTbI8" rel="noopener noreferrer"&gt;#70 Python Tutorial for Beginners | Bubble Sort in python | List Sort&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Understanding ‘g’ and ‘session’ in Flask</title>
      <dc:creator>Steph</dc:creator>
      <pubDate>Tue, 16 Apr 2024 04:11:55 +0000</pubDate>
      <link>https://dev.to/stephbert/understanding-g-and-session-in-flask-llm</link>
      <guid>https://dev.to/stephbert/understanding-g-and-session-in-flask-llm</guid>
      <description>&lt;p&gt;When you’re building a Flask web application, sometimes you run into situations where you have data that you’d like to store globally during a request or across multiple requests. This is where Flask’s built-in objects 'g' and 'session' can come in handy. In this blog post, we’ll explore what both of these objects are, similarities and differences, as well as when to use each one.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What is 'g'?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In Flask, 'g' is used to temporarily store and share data across your app within the same request context. Here are some of the key characteristics of 'g':&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Does not persist between requests:&lt;/strong&gt;&lt;br&gt;
A new instance of 'g' is created each time a client sends a request to a Flask application, so the data stored in 'g' is not persisted between different requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Accessible across functions:&lt;/strong&gt;&lt;br&gt;
The data stored in 'g' can be accessed from any function within the same request context, allowing you to share data between different parts of your app within the same request handling process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Automatically cleared at the end of each request:&lt;/strong&gt;&lt;br&gt;
At the end of each request, Flask automatically clears 'g', removing any data stored within it. This helps to make sure the data in 'g' remains isolated and specific to the current request.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Use cases for 'g'&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In certain situations 'g' can be used to dry up your code. It is often used in request decorators like @app.before_request, @app.after_request and @app.teardown_request. For example you could use 'g' to set a flag at the beginning of a request and handle it at the end. It can also be used for resource management like managing database connections.&lt;/p&gt;

&lt;p&gt;Here’s an example of how to use 'g' for managing a database connection from Flask’s &lt;a href="https://flask.palletsprojects.com/en/2.3.x/appcontext/" rel="noopener noreferrer"&gt;documentation&lt;/a&gt; on 'g':&lt;/p&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%2F8mswx3x3wzmsij7vpw74.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%2F8mswx3x3wzmsij7vpw74.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;get_db()&lt;/strong&gt; function checks if a database connection already exists in 'g'. If it does not, it establishes a new connection and stores it in g.db, that way any function during the request can reuse the same database connection. The &lt;strong&gt;teardown_db()&lt;/strong&gt; function executes when the application context ends (after the response is constructed and sent). It ensures the cleanup of the database connection and removes the connection from 'g'. &lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What is a ‘session’?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In contrast to 'g', Flask’s 'session' object is used for storing data across requests. Here are some of the key characteristics of a 'session' object:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Persists across requests&lt;/strong&gt;&lt;br&gt;
The session object is designed to store data that needs to persist across multiple requests from the same user. When is session data typically cleared? If you’re using a session for user authentication and authorization, it’s typically cleared when a user logs out. You can also set expiration periods or timeouts for your sessions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Stored on the server&lt;/strong&gt;&lt;br&gt;
Session data is stored on the server, however Flask uses client or server-side cookies to store the session identifier. Each time a request is sent to the server the client sends the cookie back to the server, the session ID is verified, and then the session data can be retrieved.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Secure&lt;/strong&gt;&lt;br&gt;
Flask secures the session data by signing it with a secret key, which helps prevent tampering. By managing sessions securely you can protect against vulnerabilities like session hacking.&lt;/p&gt;

&lt;p&gt;The metaphor I like to think of when trying to understand the concepts of 'g' and 'session' is a locker at the gym. Your &lt;strong&gt;gym session&lt;/strong&gt; represents the &lt;strong&gt;request&lt;/strong&gt;. Each time you go to the gym you put your belongings in a &lt;strong&gt;locker ('g')&lt;/strong&gt;. The locker you use is specific to your current gym session and allows you to store and access the &lt;strong&gt;items (data)&lt;/strong&gt; that you need during your workout. When you’re done with your workout, you empty your locker in the same way that at the end of each request in Flask the 'g' object is cleared. In contrast, if you were to rent a gym &lt;strong&gt;locker for a year&lt;/strong&gt;, the locker would represent a &lt;strong&gt;session&lt;/strong&gt;. You’re able to continue to go back to your locker over multiple &lt;strong&gt;gym sessions (requests)&lt;/strong&gt; to access the &lt;strong&gt;items (data)&lt;/strong&gt; that you need.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Use cases for ‘session’&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;‘Session’ is used for data that needs to persist across requests from the same user, such as user authentication and authorization, shopping carts, or user preferences. &lt;/p&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%2Fpyhw4t6w2villsz0vpjf.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%2Fpyhw4t6w2villsz0vpjf.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When a user successfully logs in, the user's ID and username are stored in the session object (session["user_id"] and session["username"]). By storing the user’s data in the session, we can securely persist the user’s identity across different requests within the same session. The logout method clears the session object by removing the user_id and username keys.&lt;/p&gt;

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

&lt;p&gt;To summarize, understanding Flask's 'g' and 'session' objects is essential for effective data management in web applications. ‘G’ provides temporary storage for data during a single request and is ideal for scenarios like database connection management. While ‘session’ stores data across requests and is useful for managing user data like authentication and authorization or shopping carts.&lt;/p&gt;

&lt;p&gt;Sources&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://flask.palletsprojects.com/en/2.3.x/appcontext/" rel="noopener noreferrer"&gt;Flask Documentation: The Application Context&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/when-should-flask-g-be-used/" rel="noopener noreferrer"&gt;GeeksForGeeks: When should Flask.g be used&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://stackoverflow.com/questions/15083967/when-should-flask-g-be-used" rel="noopener noreferrer"&gt;Stack Overflow: When Should Flask.g be used?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>How to Handle Long Lists of Conditional Statements in Python</title>
      <dc:creator>Steph</dc:creator>
      <pubDate>Tue, 26 Mar 2024 05:19:14 +0000</pubDate>
      <link>https://dev.to/stephbert/how-to-handle-long-lists-of-conditional-statements-in-python-4pa0</link>
      <guid>https://dev.to/stephbert/how-to-handle-long-lists-of-conditional-statements-in-python-4pa0</guid>
      <description>&lt;p&gt;If/elif/else statements are great for handling conditional statements in Python, but what if you have a very long list of conditions? Writing out all of the if/elif/else statements can get very tedious and repetitive. Python has two other options for handling conditional statements that can be valuable in this situation: dictionary mapping and match/case statements. We’ll dive into both of them in more detail below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dictionary Mapping&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s say you have the following if/elif/else statements representing a toddler’s activities based on their emotions:&lt;br&gt;
&lt;/p&gt;

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

if toddler == "hungry":
    activity = "Snack time, asap!"
elif toddler == "sleepy":
    activity = "Read 800 Little Blue Truck books."
elif toddler == "happy":
    activity = "Play with anything other than safe, age-appropriate toys."
elif toddler == "snuggly":
    activity = "Give mom snugs."
elif toddler == "curious":
    activity = "Try to break into all locked cupboards."
else:
    activity = "Run circles around tired parents."

print(activity)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, “if/elif toddler ==” and “activity ==” are repeated over and over, so it’s not particularly DRY. Here’s how the same code would look using &lt;strong&gt;dictionary mapping&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

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

toddler_activities = {
    "hungry": "Snack time, asap!",
    "sleepy": "Read 800 Little Blue Truck books.",
    "happy": "Play with anything other than safe, age-appropriate toys.",
    "snuggly": "Give mom snugs.",
    "curious": "Try to break into all locked cupboards."
}

activity = toddler_activities.get(toddler, "Run circles around tired parents.")
print(activity)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this version, the dictionary’s keys represent the toddler's emotions and the values represent the corresponding activities. We then use the &lt;strong&gt;get()&lt;/strong&gt; method to retrieve the activity based on the toddler's current emotion. If the emotion is not found in the dictionary, the default activity is "Run circles around tired parents."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Match/Case Statements&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Another approach to handling long lists of conditionals is to use match/case statements. This approach was introduced in Python 3.10 and is very similar to switch/case statements in JavaScript. Here’s how our code would look using match/case statements:&lt;br&gt;
&lt;/p&gt;

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

activity = match toddler:
    case "hungry":
        "Snack time, asap!"
    case "sleepy":
        "Read 800 Little Blue Truck books."
    case "happy":
        "Play with anything other than safe, age-appropriate toys."
    case "snuggly":
        "Give mom snugs."
    case "curious":
        "Try to break into all locked cupboards."
    case _:
        "Run circles around tired parents."

print(activity)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The “match” statement is used to match the value of “toddler” against the various cases, each corresponding to a toddler emotion. If no match is found ( “case_:”), the default activity is "Run circles around tired parents."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to Use Each Approach&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ultimately the choice between if/elif/else statements, dictionary mapping, and match/case statements depends on the specific requirements and preferences of your project: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;While &lt;strong&gt;if/elif/else&lt;/strong&gt; statements are great to use when you have a small list of conditionals, they can quickly become repetitive when the list becomes long. &lt;/li&gt;
&lt;li&gt;Using &lt;strong&gt;dictionary mapping&lt;/strong&gt; is a DRYer and more concise approach, however, it’s not necessarily as easy to read as if/elif/else statements because you have to read through key/value pairs. &lt;/li&gt;
&lt;li&gt;If you’re using Python 3.10 or higher, &lt;strong&gt;match/case statements&lt;/strong&gt; are a great option to use since they are both DRYER than if/elif/else statements and also more intuitive to read than dictionary mapping.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Flatiron Python Curriculum, “Control Flow: Conditional Statements” Lesson&lt;/li&gt;
&lt;li&gt;Geeks for Geeks, “&lt;a href="https://www.geeksforgeeks.org/python-match-case-statement/"&gt;Python Match-Case Statement&lt;/a&gt;” &lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Creating Controlled &amp; Uncontrolled Forms in React</title>
      <dc:creator>Steph</dc:creator>
      <pubDate>Mon, 04 Mar 2024 06:47:27 +0000</pubDate>
      <link>https://dev.to/stephbert/building-controlled-forms-in-react-3bia</link>
      <guid>https://dev.to/stephbert/building-controlled-forms-in-react-3bia</guid>
      <description>&lt;p&gt;When you’re first learning React, one of the key concepts to understand is the difference between controlled and uncontrolled components. Below we’ll dive into the key differences between the two when you’re creating a form, as well as the benefits of controlled forms so you’ll understand when to use one over the other. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are Controlled Forms?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Controlled forms are forms whose values are controlled by state. These values include input fields, text areas, and select dropdowns. As a quick reminder, state is used when a component needs to keep track of information that might change over time (eg. form inputs, storing data fetched from an API, toggling visibility of components, etc). &lt;/p&gt;

&lt;p&gt;In the example of the controlled form below, the “first”, “last” and “city” inputs are controlled by state. The handleChange function is triggered whenever there’s a change in any of the form inputs. It updates the “formData” state by calling the setFormData function and passing in the new data as an argument – spreading the existing state (making a copy of it) and adding the new key/value pairs. &lt;/p&gt;

&lt;p&gt;You’ll notice on the  elements that each element has a “name” attribute that corresponds to the key in the “formData” state and a “value” attribute that corresponds to the value in state. This setup enables the inputs to be controlled by state.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Eg. Controlled Form:&lt;/em&gt;&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";

const initialState = {
    first: "",
    last: "",
    city: ""
}

const ControlledForm = () =&amp;gt; {

    const [formData, setFormData] = useState(initialState)

    const handleChange = (e) =&amp;gt; {
        setFormData({
            ...formData,
            [e.target.name]: e.target.value
        })
    }

    const handleSubmit = (e) =&amp;gt; {
        e.preventDefault()
    // Handle form submit
    }

    return (
        &amp;lt;div&amp;gt;
        &amp;lt;form onSubmit={handleSubmit} onChange={handleChange}&amp;gt;
            &amp;lt;input type="text" name="first" value={formData.first} /&amp;gt;
            &amp;lt;input type="text" name="last" value={formData.last} /&amp;gt;
            &amp;lt;input type="text" name="city" value={formData.city} /&amp;gt;
            &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

export default ControlledForm;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note: It's typical to add the onChange to each input element. In the code above, I've taken advantage of event delegation and added it to the form element instead. This setup works in the same way as if you had added the onChange to the input, but makes the code DRYer. However, it's important to note that you will see an error message in your console (which you can ignore), since it's not the typical setup.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are Uncontrolled Forms?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In contrast, uncontrolled forms do not use state to manage their form data. They use the browser’s DOM directly to handle the form inputs and to retrieve the form data.&lt;/p&gt;

&lt;p&gt;To update our example above to an uncontrolled form, we would need to handle the form submission using references to the input fields, using the useRef hook instead of useState. In an uncontrolled form, each input needs a “ref” attribute associated with it. When the form is submitted and the “handleSubmit” function is called, the values of the inputs are retrieved using the “refs”. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Eg. Controlled Form:&lt;/em&gt;&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";

const UncontrolledForm = () =&amp;gt; {

    const firstRef = useRef("")
    const lastRef = useRef("")
    const cityRef = useRef("")

    const handleSubmit = (e) =&amp;gt; {
        e.preventDefault()
        // Access form data using refs
        const formData = {
        first: firstRef.current.value,
        last: lastRef.current.value,
        city: cityRef.current.value
        }
        // Handle form submit
        // Reset the form fields
        e.target.reset()
    }

    return (
        &amp;lt;form onSubmit={handleSubmit} onChange={handleChange}&amp;gt;
            &amp;lt;input type="text" name="first" ref={firstRef} /&amp;gt;
            &amp;lt;input type="text" name="last" ref={lastRef} /&amp;gt;
            &amp;lt;input type="text" name="city" ref={cityRef} /&amp;gt;
            &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
    )
}

export default UncontrolledForm;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Benefits of Using Controlled Forms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In React it’s best practice to use controlled forms instead of uncontrolled forms wherever possible. Here are some of the key benefits of using controlled forms:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Easier data sharing with react components&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Since the form data is managed through state, other components can easily access this data through props if needed. This creates a “single source of truth” for the form data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Predictable data management and flow using state&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Handling data through state is easier and more predictable than relying on a browser’s DOM for state management. Using the DOM to manage state can also lead to unexpected behaviors.&lt;/li&gt;
&lt;li&gt;With controlled forms, it can be easier to understand how data flows through your application since all changes to the form data are managed through state and are passed down to child components through props.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Increased data consistency through the use of immutable data&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In React, state should be treated as immutable, meaning it can’t be modified directly. When changes are made to the form data, we create a new state object with the updated form data. &lt;/li&gt;
&lt;li&gt;Since state changes are more predictable and traceable than data directly manipulated in the DOM, it’s easier to ensure data consistency in controlled forms.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Easier testing, debugging, data validation, and error handling&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Testing, debugging, data validation, and error handling are all easier to implement on controlled forms since all of the form data and state changes are managed within React components.&lt;/li&gt;
&lt;li&gt;Uncontrolled forms can sometimes need additional testing to ensure the React components and the DOM-managed state are interacting correctly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As a final note, there are a few specific situations where you will need to use an &lt;em&gt;uncontrolled&lt;/em&gt; form. For example, if you’re integrating with non-React code or third-party libraries that use traditional DOM manipulation or if you have a file upload as an input in your form.&lt;/p&gt;

&lt;p&gt;Sources: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://legacy.reactjs.org/docs/uncontrolled-components.html"&gt;React Legacy Documentation, "Uncontrolled Components"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://react.dev/reference/react/useRef"&gt;React Documentation, "useRef"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.scaler.com/topics/react/controlled-and-uncontrolled-components-in-react/"&gt;Scaler, "Controlled v/s Uncontrolled Component in React"&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>The Difference Between HTML DOM Properties: innerHTML, innerText, and textContent</title>
      <dc:creator>Steph</dc:creator>
      <pubDate>Thu, 08 Feb 2024 05:12:36 +0000</pubDate>
      <link>https://dev.to/stephbert/the-difference-between-html-dom-properties-innerhtml-innertext-and-textcontent-n10</link>
      <guid>https://dev.to/stephbert/the-difference-between-html-dom-properties-innerhtml-innertext-and-textcontent-n10</guid>
      <description>&lt;p&gt;When you’re starting out learning JavaScript it can be challenging to understand the differences between innerHTML vs innerText vs textContent. While all three are DOM properties that allow you to set or return the content of HTML elements, they each have different use cases.  Let’s start by breaking down the major differences between the three in the chart below.&lt;/p&gt;

&lt;h1&gt;
  
  
  Key Differences
&lt;/h1&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%2Fta11xob8j5pqczxd5v5y.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%2Fta11xob8j5pqczxd5v5y.png" alt="Image description" width="800" height="292"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Source: &lt;a href="https://www.w3schools.com/jsref/prop_node_innertext.asp"&gt;W3 Schools definitions&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Example
&lt;/h1&gt;

&lt;p&gt;Let’s go through an example that further illustrates the difference between the three properties.&lt;/p&gt;

&lt;p&gt;Here's our starting HTML:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;p&amp;gt; Paragraph demonstrating the &amp;lt;span style="color:purple"&amp;gt;difference&amp;lt;/span&amp;gt; between       innerHTML, innerText, and textContent.&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As well as what it looks like rendered in the browser: &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%2F21y1pegkwxzjvr0xna7j.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%2F21y1pegkwxzjvr0xna7j.png" alt="Image description" width="800" height="42"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here's the JavaScript where we're applying innerHTML, innerText, and textContent to our paragraph element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const paragraphText = document.querySelector("p");

//innerHTML//
function innerHTMLTest() {
    console.log("innerHTML:" + paragraphText.innerHTML);
}
innerHTMLTest();


//innerText//
function innerTextTest() {
    console.log("innerText:" + paragraphText.innerText);
}
innerTextTest();


//textContent//
function textContentTest() {
    console.log("innerContent:" + paragraphText.textContent);

textContentTest();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What appears in the console:&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%2Fxe5dqn7mw5jhft7dgn39.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%2Fxe5dqn7mw5jhft7dgn39.png" alt="Image description" width="800" height="241"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  When to Use Each Property
&lt;/h1&gt;

&lt;h3&gt;
  
  
  innerHTML
&lt;/h3&gt;

&lt;p&gt;innerHTML is great to use when you’re looking to see or replace the HTML content inside of an element. It can be especially helpful if you’re looking to quickly and easily replace a large amount of HTML or empty an HTML element (eg. empty a div tag using div.innerHTML = “”).&lt;/p&gt;

&lt;p&gt;To continue our example from above, you could use innerHTML to completely swap the text in our paragraph with an unordered list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const paragraphText = document.querySelector(‘p’);

paragraphText.innerHTML = “
&amp;lt;ul&amp;gt; 
    &amp;lt;li&amp;gt;List item one&amp;lt;/li&amp;gt; 
    &amp;lt;li&amp;gt;List item two&amp;gt;&amp;lt;/li&amp;gt; 
    &amp;lt;li&amp;gt;List item three&amp;gt;&amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;”;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  innerText
&lt;/h3&gt;

&lt;p&gt;innerText is used when you want to see or replace the text inside an element or node, but &lt;strong&gt;you don’t care about additional formatting like spacing&lt;/strong&gt;. This is the property that I end up using the most often when I’m trying to replace any text within an HTML element since I’m often not running into a lot of additional styling or spacing within the text.&lt;/p&gt;

&lt;h3&gt;
  
  
  textContent
&lt;/h3&gt;

&lt;p&gt;textContent is used when you want to see or replace the text inside an element or node, &lt;strong&gt;including any styling&lt;/strong&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>html</category>
    </item>
  </channel>
</rss>
