Hooks in React JS

  • By Sarika Ganesh Kore
  • March 27, 2023
  • JavaScript
Hooks in React JS

Hooks in React JS

In React we use class components and functional components to create the web application. A class component in React has extra facilities than a function component such as state and life cycle methods. To use these facilities in a function component Hooks in React JS are introduced in 16.8 version of React.

Are you looking to enhance your skills in web development with React JS? Look no further! We are excited to offer React JS classes in Pune!

There are different hooks in React that are used for different purposes. Every hook in React starts with the keyword ‘use’. All the hooks can be imported from reacting library.

Hooks in React JS 

  • useState() hook:- 

This hook is used to define and change the state. We have to destructure useState hook with two values, one is initial value and second is a function to change the state value. 

 

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

 

e.g. import React, { useState } from ‘react’

function Usestatehook() {

    const [name,setName]=useState(“ABC”)

    const [qty,setQty]=useState(0)

  return (

    <div>

      <h1>My product name is {name}</h1>

      <h2>Quantity is:{qty}</h2>    

      <button onClick={()=>setName(“PQR”)}>Change State</button><br/><br/>

      <button onClick={()=>setQty(qty-1)}> – </button> {qty} 

      <button onClick={()=>setQty(qty+1)}> + </button>

    </div>

  )

}

export default Usestatehook

  • useRef() hook:- 

This hook is used to manipulate the DOM(Document Object Model), to handle the focus and css styles like changing the color, font size etc. For using this hook we have to create a reference by ref keyword.

e.g. import React, { useRef } from ‘react’

 

function Userefhook() {

    const refer=useRef(null)

    function changestyle()

    {

        refer.current.value=”Sevenmentor”

        refer.current.focus()

        refer.current.style.color=”purple”

        refer.current.style.fontSize=”40px”

        // refer.current.style.display=”none”

    }

  return (

    <div>

      <input type=”text” ref={refer}/><br/><br/>

      <button onClick={changestyle}>Change Style</button>

    </div>

  )

}

Hooks in React JS

export default Userefhook

  • useEffect() hook:- 

There are some side effects of using class component in React while we update the DOM or while fetching the data from API. We have to use a life cycle method to control these side effects. useEffect() hook is a life cycle method which is called whenever a component is created, props are used, state is created or when state is updated. You can decide for which operation useEffect() hook should be called.

e.g. import React, { useEffect, useState } from ‘react’

function Useeffecthook() {

    const [data,setData]=useState(5)

    const [count,setCount]=useState(0)

    useEffect(()=>

    console.warn(useEffect)

    ,[count])

  return (

    <div>

      <h1>Data: {data}</h1>

      <h1>Counter: {count}</h1>

      <button onClick={()=>setData(data*3)}>Update Data</button>

      <button onClick={()=>setCount(count+1)}>Update Counter</button>

    </div>

  )

}

export default Useeffecthook

 

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

 

  • useContext() hook:-

When we create many components in React with their child and super child components then it becomes difficult to access data from child and super child components. UseContext hook is used to access data from and to child and super child components.

e.g. import logo from ‘./logo.svg’;

import ‘./App.css’;

import { createContext, useState } from ‘react’;

import Child from ‘./Child’;

import Otherchild from ‘./Otherchild’;

export const Info=createContext();

function App() {

  const [color,setColor]=useState(‘red’);

  const [day,setDay]=useState(“Wednesday”);

  const getDay=(item)=>{

    console.warn(item);

    setDay(item);

  }

  

  return (

    <Info.Provider value={{appcolor:color,getDay:getDay}}>

    <div className=”App”>

      <h1>App Component {day}</h1>

      <Child/>

      <Otherchild/>

    </div>

    

    </Info.Provider>

  );

}

export default App;

  • useReducer() hook:-

useReducer hook is similar to useState hook. It is also used to handle the state but it is used to handle the complex state. useReducer accepts two arguments reducer and initial state. Reducer is a function which handles the logic using switch case statement and initial state is a value which is generally a object. useReducer hook always returns the current state and dispatch method.

e.g. import logo from ‘./logo.svg’;

import ‘./App.css’;

import Product from ‘./Product’;

import {useState,useReducer} from ‘react’;

const initialstate=[{id:new Date(),name:”AAA”,email:”aaa@example.com”},];

function reducer(state,action)

{

  switch(action.type)

  {

    case ‘add’:

      return […state,action.obj];

      case ‘delete’:

      return (state.filter((contact)=>{

        return(

          contact.id!==action.obj.id)

        })

       );

      default:

        break;

      

  }

}

function App() { 

    const [state,dispatch]=useReducer(reducer,initialstate)

    const [name,setName]=useState(“”);

    const [email,setEmail]=useState(“”);

  const adddata=(e)=>  {

    e.preventDefault();

    const contact={

      id:new Date(),

      name,

      email

    }

    setName(“”);

    setEmail(“”);

    dispatch({type:”add”,obj:contact})

  }

  return (

    <div className=”App”>

      <h1>useReducer Hook</h1>

      <form onSubmit={adddata}>

        <input type=”text” placeholder=’name’ 

        value={name} onChange={(e)=>setName(e.target.value)}/>

        <br/>

        <input type=”text” placeholder=’email’ 

        value={email} onChange={(e)=>setEmail(e.target.value)}/>

        <br/>

        <button>Add Data</button>

      </form>

     <div>

      <ul>

        {state.map(contact=>{

          return(

          <li key={contact.id}>

            <h2>{contact.name}</h2>

            <h3>{contact.email}</h3>

            

            <div>

              <button onClick={()=>dispatch({type:”delete”,obj:{id:contact.id}})}>Delete</button>

            </div>

          </li>

          );

        })}

      </ul>

     </div>

     <Product/>

    </div>

  );

}

export default App;

  • useCallback() hook:-

This hook is used to control when a function is to be rendered. There are many situations where multiple functions are used then every time whenever a function is rendered other functions are also get called but they will not display result. This process is wastage of time. So to control this useCallback hook is used.

Don’t miss this opportunity to level up your web development skills with SevenMentor’s  React JS Course in Pune today!

  • useMemo() hook:-

This hook is similar to useCallback hook. Whenever many operations are performed at a time functions and events are called everytime automatically. This causes wastage of time. So to control this situation useMemo hook is used.

e.g. import React, { useMemo, useState } from ‘react’

 

function Usememohook() {

    const [count,setCount]=useState(0)

    const [price,setPrice]=useState(100)

    const usem=useMemo(()=>

    console.warn(count)

    ,[count])

  return (

    <div>

      <h2>UseMemo Hook</h2>

    <h3>Counter: {count}</h3>

    <h3>Price: {price}</h3>

    <button onClick={()=>setCount(count+1)}>Update Count</button>

    <button onClick={()=>setPrice(price*2)}>Update Price</button>

    </div>

  )

}

 

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

 

export default Usememohook

Users can also create a custom hook in React JS.

 

Author:-

Sarika Ganesh Kore

Call the Trainer and Book your free demo Class For React JS Call now!!!
| SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*