Most commonly used React Hooks
Published: 2021-10-16 13:24:57

We are going to learn about React hooks in this blog.
Let us start with its introduction:

Hooks are new addition to React that lets us use state, and other React features such as Lifecycle methods, without writing a class.

Types of Hooks in React are:

<b> 1.State Hook </b>
Using the useState hook lets us add a React state to our functional component.The useState function is a built-in hook that can be imported from the react package.


#### Importing useState hook from react
 & Declaring a State Variable:

In a functional component we directly call the useState hook inside our component.

```
import React, {useState} from "react";

function Example(){
const [time, setTime] = useState(0);
//..
}
```
useState hook returns a pair of values: the current state and a function that updates it. This is why we write const [time, setTime] = useState().

#### Reading a State
In a functional component we can use 'time' as :
```
  <p>You clicked {time} times</p>
```

#### Updating a state
```
<button onClick={() => setTime(time + 1)}>
    Submit
</button>
```
#### Putting together the whole code:
```
import React, {useState} from "react";

function Example(){
const [time, setTime] = useState(0);

 <p>You clicked {time} times</p>
<button onClick={() => setTime(time + 1)}>
    Submit
  </button>
}
```
<hr></hr>

<b> 2. Effect hook</b> 

The purpose of the useEffect hook is to allow us to perform side effects within a functional components. Examples of side effects we will typically perform in a React application are: data fetching, setting up a subscription, and manually changing the DOM in React components.

It accepts two arguments:

 1.callback function 
 2.Dependencies Array 

```
useEffect(callback[, dependencies]);
```
We can put side-effect logic into the callback function, then use the dependencies argument to control when we want the side-effect to run. That’s the purpose of useEffect().

<b> The dependencies of useEffect() </b> 

 Three cases with dependencies array:
<b> 1. No dependency array </b> : 
```
import { useEffect } from 'react';

function App(){
useEffect(() => {

    });
}
```

In this case, the callback gets fired after the initial rendering and everytime any of the component state changes.

<b> 2. Empty dependency array </b>:
```
import { useEffect } from 'react';

function App(){
 useEffect(() => {

    }, []);
}
```
 In this case, the callback gets fired only once after the initial rendering.


<b> 3. With dependencies </b>:

```
import { useEffect } from 'react';

function App(){
useEffect(() => {

    }, [dependency1, dependency2]);
}
```
In this case, the callback gets fired after the initial rendering and every time any of the dependencies in the dependencies array changes.

<b> Summary </b>:

useEffect(callback, dependencies) invokes the callback after initial mounting, and on later renderings, if any value inside dependencies has changed.
<hr></hr>


<b> 3. Ref hook </b>

useRef() is JavaScript function, which creates and returns a mutable JavaScript object.
This hook accepts some value and returns an object with the given value. 

<b> Syntax </b>
Importing the ref hook and setting up looks like:
```
import {useRef} from 'react';

const refContainer = useRef(initialValue);

```
#### Use cases

1.Getting access to DOM nodes
The use case of useRef() is getting access to DOM nodes. If we want to pass the value we get from useRef() as a ref prop on any React element, React will set the .current property of an element to the corresponding DOM node. This allows us to do things like grab input values or set focus, for example in the Form below:

```
import {useRef} from 'react';

const Form =() =>{

const nameRef = useRef();

//Here variable Name contains the current value of input field 
const name = nameRef.current.value; 

return(
    <>
      <label>
        Name:
        <input
          placeholder="name"
          type="text"
          ref={nameRef}  
        />
      </label>
      //Here we added an event which will set the input to focus when user clicks on the button
      <button onClick={() => nameRef.current.focus()}>
        Focus Name Input
      </button>
  </>
)
}
```
 
#### 2.Storing Values

A unique way to implement a useRef() hook is to use it to store values instead of DOM references. These values can either be a state that does not need to change too often or a state that should not trigger full re-rendering of the component. This can be used when we want to implement toggle function, for example:

```
let toggled = useRef(false);

  const handleToggle  = () => {
    toggled.current = !toggled.current;
  }

return(
<>
   <label onMouseMove={handleToggle}></label>
</>
)

```
<hr></hr>


<b> 4.Context hook </b>

useContext hook is used to create common data that can be accessed throughout the component hierarchy without passing the props down manually to each level. Context defined will be available to all the child components without involving props.


#### Importing the hook from the React library:
```
import {useContext} from 'react';
```
We call useContext() function, which accepts context object as argument and returns current context value:
```
const contextValue = useContext(MyContext);
```
The context object should be created above the useContext() hook before the hook is called (or imported from another file).

Usage of useContext() in functional component is same as we would use Context API, except that the hook works with a MyContext.Provider and MyContext.Consumer component in one call.

Let us consider, we are building app where we have a button and by clicking on it the status of authentication is changed from Yes to No.


Firstly we need to create Context:
```
// Creating the context object and passing the default values. 

export const authContext = React.createContext({status:null,login:()=>{}}); 
```
Now we import Context to our file and use it's values anywhere we find it necessary:
```
import {AuthContext} from './authContext';
import {useContext} from 'react';

export const Auth = () =>{

const auth = useContext(AuthContext); 

return ( 
    <> 
      <h1>Are you authenticated?</h1> 
      {auth.status ?  <p>Yes you are</p> :  <p>No you are not</p> 
       } 
      <button onClick={auth.login}>Click To Login</button> 
    </> 
  ); 
}
```
<b> Summary </b>

React’s useContext hook makes it easy to pass data throughout your app without manually passing props down the tree.

<hr> </hr> 
<b> References For this blog </b>
- https://reactjs.org/
- https://dev.to/olenadrugalya/basic-hooks-in-react-usecontext-4bie