useState && useEffect ⚛
Tags: react, javascript, 100daysofcode, webdev
Published: 2020-11-24 05:56:44

In `Feb 2019` React hooks were introduced to react community 
(React 16.8).
This new react feature solves one of the biggest problems faced by every react developers.

You can skip the problem section but it'll be good to know about what motivated React developers to bring hooks to the React.

# Problems
* Render props - Before Hooks, functional components were stateless due to which `state needs to be passed to the functional component through props` and if the application is `too large` then the `drilling of props` was one of the `obstacle` developers need to go through.
* High order component - HOC wraps the component to give extra power like state but it also creates `wrap hell` as the application scale and application become too abstracted.  

Let's explore Hooks now 💥

#### Hooks
***Hooks is just a group of functions which Provide extra features to the Functional component by hooking to the core feature of react.***

like State `useState()` , Lifecycle `useEffect()`

#### useState
***`useState()` is a hook function which enable developers to use State in functional component.***

`import`
```javascript
import {useState} from 'react'
```
`usage of useState`
```javascript
const [stars , setStars] = useState(3)

```
 * stars hold the initial value 3 is just like the state with the initial value.
 * setStars is the function which will set the stars like the 
   this.setState.
 * useState receive initial value.

***We can set multiple states variable by using useState again and again.***

```javascript
const [stars , setStars] = useState(3)
const [movie , setMovie] = useState("The martian")
const [userInfo , setUserInfo] =useState({
 userName:"john",
 email: "john@example.com"
})
```

###Example of useState

```javascript
import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [stars, setStars] = useState(3);
  return (
    <div className="App">
      <h1>Welcome to netflix </h1>
      <h2>The Martian</h2>
      <button onClick={() => setStars(stars + 1)}>Change Rating</button>
      <h1>{stars}⭐</h1>
    </div>
  );
}

```

`Output`
 
![Screenshot 2020-11-17 220149](https://dev-to-uploads.s3.amazonaws.com/i/8m62gau0llbrs1phrlrb.jpg)

[Demo](https://codesandbox.io/s/romantic-voice-lwwrr?file=/src/App.js:0-351)

setStars set the value of the star by incrementing one to the previous value. So every time you click the button the stars 
 increment.
Thus useState lets you to change and set state for functional component.

***Every time we set a new state value the component rerender.***


#### useEffect
***`useEffect()` is a hook function which enable developers to use group of lifecycle method like 
 componentDidMount ( ) , componentDidUpdate( ) , componentWillUnmount() in functional component.***

`import`
```javascript
import {useState , useEffect } from 'react'
```
useEffect runs after every render and most of the side effects (Like Network Request , subscription) are performed under this function.

```javascript
useEffect(()=>{
// network requests
}  
 ,[ ])
```
useEffect( ) has two parameters , function and Array variable.

1. function contains the code which you want to execute after 
  every render.


2. Array contains a state variable names for which you want to run the useEffect.

***Since the useEffect() functions are run on every subsequent re-render/update, we can tell React to skip a run, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for. React will only re-run the side effect if one of the items in this array changes.***

######Lot of English lets understand `useEffect` through code.

In this example, we will make a simple bookmark app.
This app will get a post from the API and the user can bookmark it.
Thats it! small app :).
![Screenshot 2020-11-24 111709](https://dev-to-uploads.s3.amazonaws.com/i/ht4lv99cmdnofknel7ik.jpg)
 
[Demo](https://codesandbox.io/s/relaxed-mestorf-gqsxu?file=/src/App.js)


```javascript
import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [post, setPost] = useState("");
  const [status, setStatus] = useState("Requesting....");
  const [display, setDisplay] = useState("none");

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        setPost(json.title);
        setStatus("Recieved");
        setDisplay(" ");
      })
      .catch((err) => {
        setStatus("Error");
      });
  });
  return (
    <div className="App">
      <p>{status}</p>
      <p>{post}</p>
      <button style={{ display: `${display}` }}>BookMark</button>
    </div>
  );
}
```
Thats lot of code right ?

Lets understand this in pieces.

### State part
`we have 3 state variable in this small app`

```javascript
const [post, setPost] = useState("");
const [status, setStatus] = useState("Requesting....");
const [display, setDisplay] = useState("none");
```
* `Post ` will be used to store the post received from api 
* `status` is basically used to keep track of the request status 
  (Requesting or Received).
* `display` will be used to toggle the display of bookmark button.

### Jsx part

```javascript
<div className="App">
      <p>{status}</p>
      <p>{post}</p>
      <button style={{ display: `${display}` }}>BookMark</button>
</div>
```
status of request and post will be displayed on the page along with button.

### useEffect part

```javascript

useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => response.json())
      .then((json) => {
        setPost(json.title);
        setStatus("Recieved");
        setDisplay(" ");
      })
      .catch((err) => {
        setStatus("Error");
      });
  });

```
As we know, use effect is basically used to perform side Effect (API request). So it's obvious that we will make our API request in the useEffect function.

1. `fetch` will get the post for us from API
2. As soon as we retrieve our post, setStatus will set the status 
   to `setStatus(received)` and the display of our button will be 
   toggled through `setDisplay(" ")`.
3. In any case, if we have any error in between the process the 
   `catch()` will be executed further setting the status to 
   `Error`;  

Now our little useEffect application is complete.

I hope this article somehow helped you to understand the basic concepts of hooks :smile:.
There's a lot more about hooks, so please go through the official react hooks docs too.