Basics of useState hook: How to use it and Where to put it?
Tags: beginners, react, javascript, programming
Published: 2022-10-06 22:35:34

As I went into learning React in phase 2 of my coding bootcamp, after just learning JavaScript in phase 1, I realized how much easier it could make my life. I was so excited to learn React but it came with its ups and downs. For me, the hardest concept to grasp was props and state. I had the hardest time figuring out where to put state! In the beginning I found that I would have to lift state very often. That would result in me getting confused within my code, not knowing which way was up or which way was down. 
<img width="100%" src="https://media1.tenor.com/images/f2acb3628808848e4c85576caf1653ae/tenor.gif?itemid=11802292" />
<figcaption align="center"> Don’t you love that there's a Supernatural meme for everything? </figcaption>
Don’t worry though! I will give you all the tips and tricks that helped me in figuring out how to use state and especially where to put it! Hopefully it will prevent you from making similar mistakes that I kept making. 😊

## Quick reminder of props:
Before we get into state, it's important to understand what props are: 
<blockquote> Props stand for properties and is a keyword used in React. These props pass the data between the different components [1].</blockquote>
 A component in simpler terms is a function and a prop is an argument that is passed into that function. There are two key things to remember about props: that they only get _passed down_ from a parent to a child component and that the data that is being passed down _can’t be changed_ by the child. Here is an example of using props:
```react
/components/App
import Home from "./Home";
// pass this data down as props to the child component
import user from "../data/user";
function App() {
return (
    <div>
      <Home name = {user.name} />
    </div>
  )}
export default App;
 
/components/Home
function Home(props) {
  return (
    <div id="home">
      <h1>{props.name} is a Web Developer</h1>
    </div>
  )}
export default Home;
//=> Cindy is a Web Developer
```
In this example, we are importing data from an object (user) and passing down a prop of name to the child component (Home) from the parent component (App). Now in Home, we can access the name being passed down by the use of the curly braces and dot notation: `{props.name}`. As you can see here the name being passed down from user is Cindy, there is no way to change this other than going into the object user and manually changing it. If the data is something that you want to change, well that's where the state hook comes in to save the day!

## What is a useState hook?
You might be thinking to yourself, what is a hook? Well, React says that:
<blockquote> A hook is a special function that lets you “hook into” React features. For example, `useState` is a hook that lets you add React state to function components [2]. </blockquote> **Awesome**, what is state exactly? Well state is data that is in your component, that is similar to a prop, but is expected to change over time. AKA users interacting with the DOM, for example a like button or a form submit. State is really helpful because it provides us a way of updating our data within our component. 
The way a state hook works is that `useState` returns an array with 2 variables: a reference variable to the current value of state and a setter function for setting/updating state. *An important tidbit about setter functions is that it triggers a re-render of the page every time state is changed!* This is why state is so great in comparison to vanilla JavaScript, it automatically re-renders only when it needs to based on if state is changed.
I know this can be a little confusing, especially if you are mostly a visual learner like me, so let's look at some basic steps of how to use state!
First step is to import `useState`:
```react
import { useState } from "react";
```
Second is to create your new state variable, let’s create a like button: 
```react
const [likes, setLikes] = useState(0);
```
Next use your state, we want a button to display the increasing likes:
```react
function LikeButton(){
  const [likes, setLikes] = useState(0);
  return(
  <div>
  	<button>{likes}</button>
  </div>
  )
}
```
Lastly, we want to set the state to update the number of likes every time the button is clicked:
```react
function LikeButton(){
  const [likes, setLikes] = useState(0);
  return(
  <div>
  	<button onClick={() => setLikes(likes + 1)}>{likes}</button>
  </div>
  )
}
```
And that's it! Now we have a like button that will show the amount of times it's been clicked!

## When do you need State?
React give us three great questions to review when you’re wondering whether or not you need to create state:

1. Is it passed down from a parent via props? If so, you might not need state.
2. Does it remain unchanged over time? If so, you might not need state.
3. Can you compute it based on any other existing state or props in your component? If so, you might not need state [3].

Tip💡: what I did when learning was write these on a sticky note and put it on my monitor so that I could easily refer back to it!

## What is Lifting State?  
I mentioned lifting state earlier and how when I was learning about `useState` I found myself having to lift state often. That is because I would put state in the wrong place! Lifting state is moving state to the closest common ancestor of the components that need it. In simpler terms, it is moving state up to its parent component. Note: if there isn’t a good parent component, you can always make one! 

## Where should State live? 
Lifting state as a beginner can be confusing, so knowing where state should live is important! A lot of my instructors were teaching us in the beginning to make or draw out the hierarchy of the components to help with understanding which components are parents, siblings, or children of each other. Knowing this information is great for determining where state should go. After a lot of time being stubborn and thinking I could just visualize the hierarchy in my head, I’m here to tell you that my instructors were… that’s correct, you guessed it… they were right! So after getting confused with where state should live multiple times, I eventually tried physically drawing out the components hierarchy and just like that ... CLICK!
I hope that all of you have that click moment too! So here are a few different tips and tricks for visualizing the components and deciding where state should live!

You could try simply writing/typing out a component hierarchy like this: 
```
	App
	  |- Header
	  |- List Container
		  |- List
```
Or my personal favorite, drawing out a diagram like this: 
![diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vghfmrkhqvxfyuljonjp.PNG)
<figcaption align="center">If you're doing a small project you could just draw this too, just to have it right in front of you, choose whatever way works best for you!</figcaption>
Or if you’re working on a larger project where there are a lot of components, you can use a program to help you create a diagram where you can continually add to it. This option is great because you can also add where you are putting your state in each component in your diagram as you go and keep going back to add to it as you expand your project, like this: 
![draw.io diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3jcq00puhxrujn9e8m8.PNG)
<figcaption align="center">This example is from a project that displays the name, image, and quote of characters on cards with an add new character form and a search bar!
</figcaption>
Here are some helpful programs that I found for creating diagrams: [draw.io](https://app.diagrams.net/), [Figma](https://www.figma.com/file/GBCGqs11KNeUyPksQzEMw0hr/Wireframing/duplicate?node-id=0%3A1), [LucidChart](https://www.lucidchart.com/pages/landing?utm_source=bing&utm_medium=cpc&utm_campaign=_chart_en_us_mixed_search_brand_bmm_&km_CPC_CampaignId=359804038&km_CPC_AdGroupID=1229254155804724&km_CPC_Keyword=%2Blucid%20%2Bcharts&km_CPC_MatchType=p&km_CPC_ExtensionID={extensionid}&km_CPC_Network=o&km_CPC_AdPosition=&km_CPC_Creative=&km_CPC_TargetID=kwd-76828563276432:loc-190&km_CPC_Country=44830&km_CPC_Device=c&km_CPC_placement=&km_CPC_target=&msclkid=49556ed6477816bee3780de916a53ffb), and [miro](https://miro.com/apps/?&utm_source=bing&utm_medium=cpc&utm_campaign=S%7CBNG%7CBRN%7CUS%7CEN-EN%7CExact%7CPareto&utm_adgroup=1144592546656023&utm_content=Miro&utm_term=kwd-71537701149770:loc-190&matchtype=e&device=c&gclid=&msclkid=1643ab2722611c7c926dc8187398fab6). Note: in the above diagrams I used draw.io!

## Conclusion:
I hope this helped clear up any confusion about how `useState` works and where to put state. For more resources here's a [YouTube video](https://youtu.be/0iNDB-2fg8A) and [React link](https://reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state) that I found helpful! Happy coding!🧑‍💻

Resources:
[1] “REACT PROPS: Different examples to implement react props,” EDUCBA, 12-Jul-2021. [Online]. 
[2] “Using the State Hook,” React. [Online].
[3]“Thinking in react,” React. [Online].