<?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: cmphill</title>
    <description>The latest articles on DEV Community by cmphill (@cmphill).</description>
    <link>https://dev.to/cmphill</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%2F1119767%2Fe4b7743c-8e37-4fb8-b57b-15bc4955509a.png</url>
      <title>DEV Community: cmphill</title>
      <link>https://dev.to/cmphill</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/cmphill"/>
    <language>en</language>
    <item>
      <title>Zustand State Management</title>
      <dc:creator>cmphill</dc:creator>
      <pubDate>Fri, 22 Sep 2023 22:32:44 +0000</pubDate>
      <link>https://dev.to/cmphill/zustand-state-management-5gkd</link>
      <guid>https://dev.to/cmphill/zustand-state-management-5gkd</guid>
      <description>&lt;h4&gt;
  
  
  Introduction
&lt;/h4&gt;

&lt;p&gt;Have you ever been frustrated by endless prop drilling, but were intimidated by state management solutions like Redux? Not to worry--there is a lightweight, low syntax, unopinionated solution called Zustand. Zustand allows you to create a file, called a store, that saves as many states as you like all in one file and import them in the components that you need them in. One of the great advantages of this approach is that Zustand supports variables of both primitive data types and of functions and arrays. The variables need not be related to one another in any form; you can place them all in the same store without any particular order.  Furthermore, you can selectively import the variables that you need for a component instead of a wholesale import. &lt;/p&gt;

&lt;h3&gt;
  
  
  Getting started
&lt;/h3&gt;

&lt;p&gt;The first thing you need to do to is install Zustand for your repository by running&lt;br&gt;
&lt;code&gt;npm install zustand&lt;/code&gt;&lt;br&gt;
phew. Now that we have that out of the way, we'll begin the similarly strenuous process of creating the store. In a new file, (you can name this whatever you like, but store.js(x) is convention),&lt;/p&gt;

&lt;p&gt;write &lt;code&gt;import {create} from 'zustand'&lt;/code&gt;.&lt;br&gt;
Your store is created, and now you can define variables. &lt;/p&gt;
&lt;h3&gt;
  
  
  Creating variables
&lt;/h3&gt;

&lt;p&gt;There are several approaches to managing your store, including setting up a store and then adding on states and variables later. However, I found that having one large set with all the variables I needed worked just fine for a small project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const useStore = create( set =&amp;gt; ({
    users: [],
    addUser: (user) =&amp;gt; set(state =&amp;gt; ({users: 
    [...state.users, user]
    current_user: {},
    setCurrentUser: (state) =&amp;gt; set({current_user: state}),
    logoutCurrentUser: () =&amp;gt; set({current_user: 
    null}),
    items: [],
    addItems: (item) =&amp;gt; set(state =&amp;gt; ({items: [...state.items, item})),
    clearItems: () =&amp;gt; set({items: []})
}))
 }))

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Importing and Using Variables
&lt;/h3&gt;

&lt;p&gt;Once you have your variables created, you can import them into the component(s) they are needed for. If you are only including one or two variables, you can import them 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;in your component:
//Example.jsx component
import useStore from "../store" //=&amp;gt; This will be whatever the relative path to your store component is

function Example() {
   const current_user = useStore((state) =&amp;gt; state.current_user)
const setCurrentUser = useStore((state) =&amp;gt; state.setCurrentUser)

   function setUser() {
    fetch("/api/login")
    .then((res) =&amp;gt; res.json())
    .then((user) =&amp;gt; {
    setCurrentUser({
     id: user.id,
     username: user.username,
    })
  }
}


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

&lt;/div&gt;



&lt;p&gt;This simple implementation of store worked just fine for my small project. I used useEffect and the promise-based nature of fetches to manage asynchronous operations. However, Zustand is capable of handling async and it allows you to bundle variables together to re-render when the value of one changes. &lt;/p&gt;

&lt;p&gt;One of the things you will want to do frequently once you have updated the state is to read it, of course. When you simply need the value of the state to render text in a DOM element, for example, you can assign it to a variable using the built in method on the store:&lt;br&gt;
&lt;code&gt;const user = useStore.getState.user&lt;/code&gt;. In this way you can access the value without updating it whenever you need to.&lt;/p&gt;

&lt;p&gt;For example, you could write a store in this fashion:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const marbleStore = create((set) =&amp;gt; ({
    marbles: {},
    fetch: async(marbleBag) =&amp;gt; {
    const response = await fetch(marbleBag)
    set({marbles: await response.json()})
}
}))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are many such applications, including updating the re-rendering the component whenever one of the specified states from within the component changes. &lt;/p&gt;

&lt;h3&gt;
  
  
  Summary of Zustand Benefits
&lt;/h3&gt;

&lt;p&gt;There are many advantages that make Zustand a great choice for a variety of projects. One is that it uses the logic of React hooks and (depending on how you use it, context). Doing so means that you don't have to write a lot of extra code to get started, and the library is quite small (less than 2kB, so it won't weigh down your repository). Because it is simple, it allows you to enter the world of state management without too much hassle. Another nice feature is the documentation. It provides many practical examples of the code in use as well as links to a sandbox where you can test out variations. Zustand automatically determines which which state a component needs and subscribes it, so no developer input is necessary in simple cases. Zustand also lets you persist data, meaning that when a user refreshes the page, the data the was previously rendered will still be saved in state. This is a great addition to forms and other pages geared toward user interaction so that progress is not lost. &lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Zustand is a powerful library that is easy to get started with and offers a simple way to manage state across many components. You can manage async, set re-renders, persist the data, and subscribe to changes in other variables to fully customize your store's function. However, if you are simply looking for an easy, but more functional alternative to useState, you can use Zustand without a lot of extra bells and whistles.&lt;/p&gt;

</description>
      <category>zustand</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>react</category>
    </item>
    <item>
      <title>Using Formik to Create React Forms</title>
      <dc:creator>cmphill</dc:creator>
      <pubDate>Tue, 05 Sep 2023 04:24:30 +0000</pubDate>
      <link>https://dev.to/cmphill/using-formik-to-create-react-forms-1aim</link>
      <guid>https://dev.to/cmphill/using-formik-to-create-react-forms-1aim</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;There's no two ways about it--creating forms in react is a pain. Not to worry: formik includes custom hooks and ready compatibility with yup validations to make creating the form and validating fields a breeze. I will walk you through the process of importing formik, writing forms, and validating fields using yup. &lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;p&gt;The first thing that you need to do is navigate to the repository that you want to create a form in. Depending on your package manager preference, run either&lt;br&gt;
&lt;code&gt;npm install formik --save&lt;/code&gt;&lt;br&gt;
or &lt;br&gt;
&lt;code&gt;yarn add formik&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In the component in which you will be creating the form, include this import line: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;note that in its simplest form, the only import formik requires is the useFormik hook. If you went this route, you would define your initial values within the hook as well as your validation schema. Unfortunately, this approach requires typing formik  all over your form. For this reason, I recommend importing the Formik, Field, Form, and ErrorMessage hooks in your import statement. It will save you a lot of pain later on.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once you have installed and imported formik, you have the option to install yup to validate your form fields. You can do this by running &lt;code&gt;npm install yup&lt;/code&gt; . To ensure that you have all the validations that you need, you can import all in your component with &lt;code&gt;import * as Yup from yup&lt;/code&gt;. &lt;/p&gt;
&lt;h2&gt;
  
  
  Implementation
&lt;/h2&gt;

&lt;p&gt;Once you have the packages installed, it is time to build the form. As with standard react forms, you define a function in the component and set its return to the form fields. Formik requires default values to be defined for each element of the form, similar to the requirement for a default state in a useState hook. The method of validation is also specified (using yup if you imported it) For example, if you were running a haberdashery, you might want a form to add new hats to your collection. Here is some example code of how you might implement that using a formik form:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

function HatForm({ addHat }) {
  const [errors, setErrors] = useState([]);

  return (
    &amp;lt;Formik
      initialValues={{
        hatName: '',
        hatCost: 0,
        hatStyle: '',
        hatMaterial: '',
      }}
      validationSchema={Yup.object({
        hatName: Yup.string()
          .max(20, 'must be 20 characters or less')
          .required('required'),
        hatCost: Yup.number('must be a number').required('required'),
        hatStyle: Yup.string().max(10, 'must be 10 characters or less'),
        hatMaterial: Yup.string().max(10, 'must be 10 characters or less'),
      })}
      onSubmit={(values) =&amp;gt; {
        fetch('http://localhost:5555/hatform', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json', 
          },
          body: JSON.stringify(values),
        })
          .then((res) =&amp;gt; {
            if (res.ok) {
              res.json().then((values) =&amp;gt; addHat(values));
            } else {
              res.json().then((errors) =&amp;gt; {
                console.log(errors);
                setErrors(errors.message);
                console.log(errors);
              });
            }
          });
      }}
    &amp;gt;
      &amp;lt;Form&amp;gt;
        &amp;lt;label htmlFor="hatName"&amp;gt; Hat Name &amp;lt;/label&amp;gt;
        &amp;lt;Field name="hatName" type="text" /&amp;gt;
        &amp;lt;ErrorMessage name="hatName" /&amp;gt;
        &amp;lt;label htmlFor="hatCost"&amp;gt; Hat Cost &amp;lt;/label&amp;gt;
        &amp;lt;Field name="hatCost" type="number" /&amp;gt;
        &amp;lt;ErrorMessage name="hatCost" /&amp;gt;
        &amp;lt;label htmlFor="hatMaterial"&amp;gt; Hat Material &amp;lt;/label&amp;gt;
        &amp;lt;Field name="hatMaterial" type="text" /&amp;gt;
        &amp;lt;ErrorMessage name="hatMaterial" /&amp;gt;
        &amp;lt;button type="submit"&amp;gt; Submit &amp;lt;/button&amp;gt;
      &amp;lt;/Form&amp;gt;
    &amp;lt;/Formik&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's it! (For your frontend form, at least). You may have noticed that there is an &lt;code&gt;addHat&lt;/code&gt; prop in the function declaration. That is because you will likely want to have your hats saved at a higher level in a multi-component website. Once the data has been JSON-ified, it needs to saved in state at the level that suits your project's requirements.  As I mentioned earlier, there are different imports that you can import (or not). This is something to be aware of as you begin writing forms in Formik--there are several different ways to write the form that vary in complexity and abstraction. Fortunately, you can view these different approaches right on &lt;a href="https://formik.org/docs/tutorial"&gt;Formik's Official Website&lt;/a&gt;. One of the questions you may have as a new programmer is "why would you include validations on the frontend when the form will be rejected by validations on the backend anyway if the form submission is not within the specifications?" That is a good question, and it fundamentally comes down to user experience. Even if your server returns an error code to the POST request, it may not be visible (or mean much) to your visitor. Frontend validations allow instant feedback to be provided to the user letting them know they need to adjust their input to the field. Another thing to note about handling the errors is that there are several ways to record and display them. You can define an error display element under each form field, or you can have them display as a block that is mapped through at the bottom of your form. &lt;/p&gt;

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

&lt;p&gt;Formik provides a nice upgrade over vanilla react forms. You no longer have to worry about overriding the default behavior of the form submission, and some of the repetitive aspects of typing out forms are no longer required. Depending on how much abstraction you are comfortable with, you can save a great deal of typing. Otherwise, you can use one of the more explicit methods for writing a formik form, and still reap the benefit of easier validations. The choice is up to you.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>CRUD in Python SQLite</title>
      <dc:creator>cmphill</dc:creator>
      <pubDate>Sat, 12 Aug 2023 22:33:20 +0000</pubDate>
      <link>https://dev.to/cmphill/crud-in-python-sqlite-2cek</link>
      <guid>https://dev.to/cmphill/crud-in-python-sqlite-2cek</guid>
      <description>&lt;p&gt;In almost all programs there is a need to create, read, update, and delete information. All of these operations can be performed with Python code that interfaces with SQLite. The first thing that needs to be done to use CRUD is to create relational databases. This &lt;a href="https://github.com/learn-co-curriculum/python-p3-cli-project-template"&gt;CLI Template&lt;/a&gt; was provided in the curriculum of the software development course at Flatiron School, and is a good starting point for someone creating their first project. Once you have forked and cloned the repository, you need to make sure that sqlite is installed on your machine. You can run &lt;code&gt;sqlite3 --version&lt;/code&gt; to check. If it is not, run &lt;code&gt;brew install sqlite&lt;/code&gt; on Mac to install it. It is also recommended to install VSCode's SQLite extension so that you can view the databases that you create. Once these are installed, you can proceed to creating your tables. For the purposes of this walkthrough, I will skip to CRUD operations once the tables have been created in the models.py file. &lt;/p&gt;

&lt;p&gt;Suppose you have three tables: a cheeses table, a dairy plants table, and a consumer table. In this instance, the cheeses table would be the join table for a many-to-many relationship, because there are many dairy plants that produces many cheeses, and there are many consumers that consume many cheeses. After creating the tables with appropriate columns, such as "id", "location" and "name" for the dairy plants, "id", "type" , "dairy plant id", and "consumer id" for the cheeses, and "id", "name" and "age" for the customer. In the cli.py file, there could be conditional selections to create instances (rows) of each table. 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;from db.models import DairyPlant, Cheese, Consumer
from db.dairy_plant import add_dairy_plant
from db.cheese import add_cheese
from db.consumer import add_consumer
if __name__ == '__main__':
    print("Welcome to the Dairyland CLI!")
while True:
    print("Choose an Option:")
    print("Add Dairy Plant")
    print("Add Cheese")
    print("Add Consumer")

if selection == '1':
    name = input("Enter Dairy Plant Name: ")
    location = input("Enter Dairy Plant Location: ")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similar logic can be added to the other two categories to create additional entries. Moving on to read functions, a fourth option could be added to the CLI list to view existing entries. Within this option, there can be sub-options to update each table:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if selection == '4':
    print("Choose a Table to View")
    print("1. View Dairy Plants")
    print("2. View Consumers")
    print("3. View Cheeses")

    view_option = input("Enter your choice.")
    if view_option == '1':
        session = Session()
        dairy_plants = session.query(DairyPlant).all()
        session.close()

        print("Dairy Plants: ")
        for dairy in dairy_plants:
            print(f"ID: {dairy.id}, Name: {dairy.name} 
            Location: {dairy.location}")
## continue the same pattern for the remaining tables.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To update existing entries, a fifth option could be added to the CLI, and the format would be the same as the read until the update logic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if update_option == '1':
   dairy_id = input("Provide the ID of the dairy plant you 
   want to update")
   dairy = 
   session.query(DairyPlant).filter_by(id=dairy_id).first()

   if dairy:
       print("Current Dairy Plant: "
       print(f"Name: {dairy.name}, Location: 
       {dairy.location}")

       new_name = input("Enter new name or press Enter to 
       skip")
       new_location = input ("Enter new location or press 
       Enter to skip")

       if new_name:
           dairy.name = new_name
       if new_location:
           dairy.location = new_location
       session.commit()
       session.close()
       print("Dairy Plant updated.")
  else:
      print("Dairy Plant does not exist."
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, you can create an option to delete existing items:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if selection == '6':
    print("choose an option :")
    print("1. Delete Dairy Plant")
     ...
    delete_option = input("Enter your choice:")

    if delete_option == '1':
        dairy_id = input ("Enter the ID of the plant to 
        delete")
        session = Session()
        dairy = 
        session.query(DairyPlant).filter_by 
        (id=dairy_id).first()

        if dairy:
            session.delete(dairy)
            session.commit()
            session.close()
            print("Dairy plant deleted successfully.")
        else:
            print("Dairy plant does not exist.")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a basic overview of how to complete CRUD operations in a simple CLI project using Python and SQLite. It is important to remember that if you are going to make changes to the structure of the tables after instantiating them, it is necessary to run &lt;code&gt;alembic upgrade head&lt;/code&gt; or the simpler (and my preference) method of deleting the .db database files and regenerating them after making the required changes. Once you have a large amount of data that you don't want to lose stored in the tables, it makes sense to spend the time and effort on mastering alembic so that changes can be made without starting from scratch. However, for a simple learning project it is much more straightforward to delete the whole table. You will need to exit the CLI interface, which you can do with &lt;code&gt;ctrl + d&lt;/code&gt;. after that, you will need to run &lt;code&gt;python cli.db&lt;/code&gt; again to enter the interface again to check your work. Make sure that updates are included in the models.py file, where the tables are designed, the cli.py file where the CRUD methods are defined, and in your seed.py file(to make test data).&lt;/p&gt;

</description>
      <category>sql</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Dealing with Imposter Syndrome</title>
      <dc:creator>cmphill</dc:creator>
      <pubDate>Fri, 11 Aug 2023 03:34:56 +0000</pubDate>
      <link>https://dev.to/cmphill/dealing-with-imposter-syndrome-2bcf</link>
      <guid>https://dev.to/cmphill/dealing-with-imposter-syndrome-2bcf</guid>
      <description>&lt;p&gt;Beginning something new is always difficult. Coding is like learning a new language and trying to think in a different way in the new language--at the same time. My journey with coding so far has been rife with imposter syndrome; I feel that I am unqualified(true at the moment) and that I cannot become qualified(a self-fulfilling prophecy I am struggling against). The most optimistic approach to dealing with imposter syndrome is to wholeheartedly believe in one's own intrinsic capabilities and disbelieve in the possibility of failure. This approach, depending on one's confidence and actual learning capacity, may be a suitable approach. In my case, I am too aware of the fact that I learn more slowly than others and have failed at enough things to follow take the aforementioned approach to dealing with imposter syndrome. &lt;br&gt;
What to do? Give up? If I did, then I would fulfill the prophecy of failure that I have imagined. If anything worthwhile is to be achieved in this life, it must be achieved through pain and struggle. The viable option in my case is to frankly acknowledge that success is not a guarantee, but continuing to strive anyway despite self-doubts. I am inspired by a quote from Theodore Roosevelt's 1899 speech, "The Strenuous Life":&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Far better it is to dare mighty things, to win glorious triumphs, even though checkered by failure, than to take rank with those poor spirits who neither enjoy much nor suffer much, because they live in the gray twilight that knows not victory nor defeat.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What words to live by. Though I do not want to cultivate an unrealistic belief that I am capable of achieving anything (I am not), or that I will be the best at whatever I attempt (I will not), I have taken to heart the belief that it is better to work hard and let the outcome be what it may. This mentality releases me from the stress of trying to control outcomes, which cannot be directly chosen. Instead, it is by doing the things that I can control--dedicating myself to study, practicing what I have studied, and by seeking advice from those smarter and more experienced than myself--that I can increase the odds of getting the outcome I desire. It is this dedication to the mundane and dogged persistence that makes people truly great. Thomas Edison said "Genius is one percent inspiration and ninety-nine percent perspiration." Likewise, Albert Einstein said "It's not that I'm so smart, it's just that I stay with problems longer." &lt;/p&gt;

&lt;p&gt;Though I cannot guarantee what the outcome ultimately will be from these studies, failure that follows strenuous effort is in my opinion far preferable to fearful stagnation. &lt;/p&gt;

&lt;p&gt;Given that it is the mundane actions which are in our control and which are the primary determinants of success or failure, attention should be given to carrying them out. One simple, widely known, and only sometimes practiced principle is to focus on one day at a time, one task at a time. Though it is simple to understand, it is difficult in practice. I want to project myself into the future and worry about what I will have achieved by that point. However, it is a far more useful application of brain power to focus the present.&lt;/p&gt;

&lt;p&gt;In the present, one needs to focus on establishing rituals for success. Having a set time and location to study makes it easier to switch gears from relaxation to work. Another is making sure to get enough rest. This is one of my favorite tips for success because sleeping is pleasant and making time for it is the the only significant challenge. Making sure to ask plenty of questions is important as well. Beginning with the pre-work, I was reluctant to seek help and this led to long periods of frustration and little action. I have been seeking assistance from my peers and from instructors, which has greatly aided the learning process. Taking breaks is important as well. I tried studying for long periods of time without taking any breaks. Not only was this unpleasant, my productivity also suffered. It is not easy to continue studying intensively without making time for rest and leisure. &lt;/p&gt;

&lt;p&gt;Learning something new is rarely an easy process, and imposter syndrome can make it worse. One can choose optimism, grim determination, or giving up to cope with these feelings. Though the going is difficult, I have been trying to do the small things right and hopefully that will pay off in the end. No matter what happens, it will be preferable to have tried and failed rather than never to have attempted. As Shakespeare said, "Our doubts are traitors, And make us lose the good we oft might win, By fearing to attempt". The biggest challenge is to acknowledge my fears but not to be overcome by them.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>motivation</category>
    </item>
    <item>
      <title>React Hooks- UseState</title>
      <dc:creator>cmphill</dc:creator>
      <pubDate>Fri, 14 Jul 2023 16:30:28 +0000</pubDate>
      <link>https://dev.to/cmphill/react-hooks-usestate-1a4f</link>
      <guid>https://dev.to/cmphill/react-hooks-usestate-1a4f</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;JavaScript is a powerful language that can be used to handle the logic of a program. Unfortunately, vanilla JavaScript often requires more code to accomplish tasks than using a framework like React. Every discrete step or action that must occur needs to be explicitly defined, making it a chore to write more complex programs. Fortunately, the React framework greatly reduces the amount of code necessary to accomplish the same task. One of the central components of React is hooks-- methods that allow us to separate the portion of a function that uses stateless logic, and the state which the function is used to process. One of the most common hooks, and the one that we have worked with the most in the Flatiron curriculum, is &lt;code&gt;useState&lt;/code&gt;. As the name implies, this hook is used to set state. State means that changes to information made by interaction with pages, amongst other factors, can be saved to a variable that can be updated and referenced. for example, if I want to keep track of cats, I could define a state for cats as follows: &lt;code&gt;const [cats, setCats] = useState ([])&lt;/code&gt;. This code says that the state is cats, using setCats will update my cats state, and the state defaults to an empty array until changes are made (e.g. fetching a data source that contains cats). Now having introduced the rationale and a use case for useState, I will describe the steps for using it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using useState
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;The hook must be imported. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Inside the component in which the hook will be used, it needs to be imported. This means you are telling your program that it needs to reference this predefined hook from react's library. At the top of the component file, there should be an import line that looks 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 {useState} from 'react'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are using multiple hooks, the curly brackets can contain multiple comma-separated hooks that you want to use. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; The state must be defined.
As mentioned above, you can identify something that you want to reference often and update. The big advantage of a state over a simple array or object that is modified within the context of the function is that it is far easier to scope the data when it is contained in state. It can become confusing very quickly when information is needed in multiple locations and multiple functions may need to modify it. Declaring a global variable is possible, but somewhat inefficient and clunky.
&lt;/li&gt;
&lt;/ol&gt;

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

&lt;/div&gt;



&lt;p&gt;Now, with my cats set to state, I can add cats from a fetch request, use another fetch to add cats or to delete them, and I can pass cats into functions for conditional rendering. This greatly improves the ease of implementing search, filter, and hide capabilities for a collection of properties. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Avoiding pitfalls
When modifying the state, it is advisable to do so nondestructively when possible. Instead of directly pushing a new property to the array, using a spread operator and defining a new constant is considered good practice. For example, if I want to add a new cat, I could do the following:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const newCatAdd = [...cats, newCat];
setCats(newCatAdd)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, I could have a function that returns a &lt;code&gt;newCat&lt;/code&gt; as a product of a form that is filled in. This can then be appended to the list of cats and the &lt;code&gt;newCatAdd&lt;/code&gt; could be referenced when rendering the page. This way, every time a new cat is added, the change in state will cause re-rendering of the JSX element that references the &lt;code&gt;newCatAdd&lt;/code&gt; variable. It is important to note that when appending data to an existing dataset, such as a db.json file, matching the structure of the existing objects is imperative for the new information to render correctly. The useState can include keys with default values of empty strings that match the format of the existing data. 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;const [cats, setCats] = useState({
furColor: "",
breed: "",
energyLevel: "",
favoriteFood: "",
 })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;React provides many advantages and greater ease in coding compared to vanilla JavaScript. Hooks are fantastic tools for manipulating information. useState allows information to be referenced in multiple places and easy modification of that data. There are many resources that provide more information on hooks, some of which I referenced in writing this post. &lt;a href="https://react.dev"&gt;https://react.dev&lt;/a&gt;  is a great starting point. It includes how-tos, introductions to the concepts of react, and is easy to read. I also recommend using MDN &lt;a href="https://developer.mozilla.org"&gt;https://developer.mozilla.org&lt;/a&gt; for support. Some articles are a bit too technical for a beginner like me, but the articles contain many cross-references with explanations of related and prerequisite topics. If you are familiar with the format of Wikipedia and find it useful, you will like using MDN. &lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>programming</category>
      <category>reacthooks</category>
    </item>
  </channel>
</rss>
