useState(), and the useEffect() Hooks
Published: 2022-09-07 20:49:52


When react was first introduced the best way to or the only way really to declare or use a state was to create it in a class component, but with the introduction of hooks declaring and using state inside a function component became possible and the most adopted way of doing just that.
Hooks are React functions that allow our react function components the ability to call and use state. Currently the most used hooks within React are the useState, and the useEffect hook, and within this post I will be going over a basic rundown of these two hooks.
#### useState():
Definitely the most use hook in React is the useState hook. Now normally variable the are used within a function disappear when the function is exited, but a state variable is preserved by React. The way you would use state before hooks was you had to declare state within a Class component by using this.state, but unlike Classes useState doesn't need to be an object. It is simply a state variable declared by writing what it will be called along with useState.
#### Declaring useState():
First we need to import the hook from React, we can do this at the top of the component we want to declare state in by simply typing.
import {useState} from 'react';
Now we have imported the useState hook how about we use it and we can do that by declaring our state variable like so.
ex: const [count, setCount] = useState(0);
now lets break this down a little bit. 
count is our state variable:
the 0 withing the () is the initial count that it is set to
and setCount: will be what we can use to modify and update our count state.
#### Rendering State:
Rendering state is just as simple as declaring it 
instead of the old way of doing it with class components.
ex: <>This is the current {this.state.count}.</>
in a function we can use it directly
ex: <>This is the current {count}.</>
#### Updating State:
To update state in a class we would have to call setState() to update the count state
ex: <button onClick={() => this.setState({count: this.state.count + 1})}>count +</button>
with the useState hook we already have setCount and count as variables so we no longer have use for the this method.
ex: <button onClick={()=> setCount(count + 1)}>count +</button>
#### Rundown:
1. we imported our state who from react
2. we declare our state variable inside of function component and set the initial value of our variable to 0
3. We updated our count variable every time we click that button which calls setCount and give it a new value. React will then re-render the component pass the new count value to it.

####useEffect():
The useEffect() hook allows you to preform <u>side effects</u>. A function component will use props and/or state to calculate an output. If the calculation doesn't target the output value, then these calculations are what we call <u>side-effects</u>.
Some example of <u>side-effects</u> are fetch requests, manipulating the DOM directly, using functions like setTimeout(), etc.
Now the rendering of the components and the rendering of the side-effect logic is independent. It would be incorrect to have your side-effects preform directly inside of the body of you component, which is primarily used to compute an output, and how often a component renders isn't something you can control - if React wants to render a component it will do so with or without your permission.
So how do you decouple rendering from the side-effect. You use <u>useEffect()</u> the hook that runs side-effects independently of rendering.
<u>useEffect()</u> will take in 2 arguments:
1. the callback: which is the function containing the side-effect logic. callback is executed right after changes are pushed to the DOM
2. dependencies is a an optional array of dependencies, useEffect() executes a callback only if the dependencies have changed between renders.
so you put your side-effect logic into the callback function, then use the dependencies argument to control when you want to fire that side-effect. That is the purpose of useEffect().
#### Dependencies:
As stated above the dependencies argument lets you control when a side-effect will run.
   -When a dependency is not provided the side-effect will run after every rendering.
   -when an empty array [] is used, the side-effect runs only once after the initial render.
   -When props or state values are used as dependencies. The side-effect will only run when any of the dependency value changes.
#### Cleanup: 
Some of side-effects will need to be cleaned up: close a socket, or clear times. Now if the callback of useEffect() returns a function, then this will be considered an effect cleanup.
cleanup works like so:
1. after the initial render, useEffect() will invoke the callback having the side-effect.
2. on later renders, before the next callback, useEffect() invokes the cleanup funtion from the previous side-effect excecution, then runs the current side-effect
3.After unmounting from the component, useEffect() invokes the cleanup funtion from the latest side-effect.
##### In Practice:
useEffect() can preform a data fetching side-effect.
-Inside you component function

```
useEffect(() => {
    fetch('api being fetched')
     .then(response => response.json())
     .then(data => console.log(data)}, [])
```

useEffect() starts the fetch request by calling an async funtion.
when the fetch request is completed we then take whatever data may come from the fetch and log it into our console, and the empty [] ensures we only run the fetch once at the initial render.
So in conclusion the useEffect() hook is the hook that manages side-effects in functional components`