DEV Community

SangeetaGogoi
SangeetaGogoi

Posted on

Most commonly used React Hooks

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:

1.State Hook
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);
//..
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Updating a state

<button onClick={() => setTime(time + 1)}>
    Submit
</button>
Enter fullscreen mode Exit fullscreen mode

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>
}
Enter fullscreen mode Exit fullscreen mode

2. Effect hook

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]);
Enter fullscreen mode Exit fullscreen mode

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().

The dependencies of useEffect()

Three cases with dependencies array:
1. No dependency array :

import { useEffect } from 'react';

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

    });
}
Enter fullscreen mode Exit fullscreen mode

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

2. Empty dependency array :

import { useEffect } from 'react';

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

    }, []);
}
Enter fullscreen mode Exit fullscreen mode

In this case, the callback gets fired only once after the initial rendering.

3. With dependencies :

import { useEffect } from 'react';

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

    }, [dependency1, dependency2]);
}
Enter fullscreen mode Exit fullscreen mode

In this case, the callback gets fired after the initial rendering and every time any of the dependencies in the dependencies array changes.

Summary :

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


3. Ref hook

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.

Syntax
Importing the ref hook and setting up looks like:

import {useRef} from 'react';

const refContainer = useRef(initialValue);

Enter fullscreen mode Exit fullscreen mode

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>
  </>
)
}
Enter fullscreen mode Exit fullscreen mode

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>
</>
)

Enter fullscreen mode Exit fullscreen mode

4.Context hook

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';
Enter fullscreen mode Exit fullscreen mode

We call useContext() function, which accepts context object as argument and returns current context value:

const contextValue = useContext(MyContext);
Enter fullscreen mode Exit fullscreen mode

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:()=>{}}); 
Enter fullscreen mode Exit fullscreen mode

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> 
    </> 
  ); 
}
Enter fullscreen mode Exit fullscreen mode

Summary

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


References For this blog

Top comments (0)