Introduction
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 useState
. 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: const [cats, setCats] = useState ([])
. 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.
Using useState
- The hook must be imported.
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:
import {useState} from 'react'
If you are using multiple hooks, the curly brackets can contain multiple comma-separated hooks that you want to use.
- 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.
const [cats, setCats] = useState ([])
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.
- 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:
const newCatAdd = [...cats, newCat];
setCats(newCatAdd)
In this case, I could have a function that returns a newCat
as a product of a form that is filled in. This can then be appended to the list of cats and the newCatAdd
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 newCatAdd
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:
const [cats, setCats] = useState({
furColor: "",
breed: "",
energyLevel: "",
favoriteFood: "",
})
Conclusion
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. https://react.dev 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 https://developer.mozilla.org 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.
Top comments (1)
Great explanation Cooper