Contact Form Background

Blog


  • BlogsReact
  • Everything You Need To Know About Hook In React

By Aspire Softserv 17 Aug 2022

Everything-You-Need-To-Know-About-HOOK-IN-REACT.webp

Welcome friend, In the ‘Everything You Need To Know About HOOK IN REACT’ blog post, We will cover all about hook concepts in react like what is a hook in react, types of react hooks, basic hooks, additional hooks, timer hooks, navigation hooks, custom hook creation rules with example brief explanations.

Let’s refresh react knowledge first – react vs angular, React Introduction, and 5-minute guide create-react-app.

What is Hook in React?

A hook is a special function that allows one to use state and other React features without writing ES6 class components which are generally considered complex to understand, use, and master.

Prerequisites

  • Node js
  • NPM
  • Install Create-react-app tool
  • Any Text Editor (Recommended- Visual Studio) 

What is Hook in React

Hooks in React are a new addition to React 16.8. They allow you to use state and other exciting React features without writing a class.

Rules of Hook in react

Hooks are simple to the basic JavaScript functions but they require the below rules.

  1. Hooks should remain at the top level of your written component
  2. Never call hooks in loops, logic conditions, or nested functions.
  3. Hooks should call only from functional components.
  4. Never call Hooks from the regular javascript functions.
  5. Hooks can call other Hooks

React Basic Hooks

React Basic Hooks present the most commonly required functionalities in stateful React apps. They are as follows:

  1. React useState
  2. React useEffect
  3. React useContext

Hook state is the new approach of declaring a state in React app

1. React useState:

What:   useState Hook in react uses the useState() functional component for setting and retrieving state

  • In the below syntax, Hook returns a stateful value (state) and a setter function (setState) to update the value.
  • The useState Hook is used to process with the state in React. We can use it as follows:

Syntax:

import { useState } from 'react'
  const [ state, setState ] = useState(initialState)

Example:

Let us understand, In the below example, Hook’s state the count is defined as a state variable, and setCount is defined as a setter function.

App.js

import React, { useState } from 'react';  
    function CountingApp() {  
    // Here "count" is a new state variable   
    const [count, setCount] = useState(0);  
      return (  
      <div>  
        <p>  Total Counter Number -  {count} times</p>  
        <button onClick={() => setCount(count + 1)}> Increment Counter  </button>  
      </div>  
    );  
  }  
  export default CountingApp; 

Note: The useState Hook here replaces this.state & this.setState().

2. React useEffect:

What: “The useEffect in react Hook technique is used to in place of the lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount methods”

Use: There are the subsequent uses of the useEffect() function as below.

  1. The useEffect Hook in react is used to deal with effect code, such as requests, timers, code optimization, subscriptions.
  2. useEffect Hook in react js deals alike as a function on componentDidMount and componentDidUpdate. This Hook allows for returning a cleanup function from it, which works like adding a function to componentWillUnmount.

Syntax:

import { useEffect } from 'react'
  useEffect(didUpdate)

Example:

Before useEffect in React hook Example

import React, { Component } from 'react';
  export default class Invitation extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        firstName: window.localStorage.getItem('firstName') || '',
        lastName: window.localStorage.getItem('lastName') || ''
      };
      this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
      this.handleLastNameChange = this.handleLastNameChange.bind(this);
    }
    handleFirstNameChange = (e) => this.setState({ firstName: e.target.value });
    handleLastNameChange = (e) => this.setState({ lastName: e.target.value });

componentDidUpdate() { window.localStorage.setItem('firstName', this.state.firstName), [this.state.firstName]; window.localStorage.setItem('lastName', this.state.lastName), [this.state.lastName]; } render() { return ( <div> <input value={this.state.firstName} onChange={this.handleFirstNameChange} /><br /> <input value={this.state.lastName} onChange={this.handleLastNameChange} /> <p> <span>Your Full-Name: {this.state.firstName} {this.state.lastName}</span> </p> </div> ); } }

After useEffect in React hook Example

import React, { Component, useState, useEffect } from 'react';
  export default function Invitation() {
    const [firstName, setFirstName] = useState(() =>
      window.localStorage.getItem('firstName') || ''
    );
    const [lastName, setLastName] = useState(() =>
      window.localStorage.getItem('lastName') || ''
    );
    const handleFirstNameChange = (e) => setFirstName(e.target.value);
    const handleLastNameChange = (e) => setLastName(e.target.value);
useEffect(() =&gt; {
  window.localStorage.setItem('firstName', firstName);
  window.localStorage.setItem('lastName', lastName);
});

return (
  &lt;div&gt;
    &lt;input value={firstName} onChange={handleFirstNameChange} /&gt;&lt;br /&gt;
    &lt;input value={lastName} onChange={handleLastNameChange} /&gt;
    &lt;p&gt;
      Your Full-Name:  &lt;span&gt;{firstName} {lastName}&lt;/span&gt;
    &lt;/p&gt;
  &lt;/div&gt;
);

}

3. React useContext

What: “useContext Hook in react accepts a context object and returns the current context value.”

useContext Use: 

  1. The useContext Hook in react is used to deal with the context in React.
  2. The useContext Hook in react replaces context consumers.

Example:

import { useContext } from 'react'
  const value = useContext(MyContext)

Additional React Hooks

There are additional hooks in react as beneath

  1. React useRef
  2. React useReducer
  3. React useMemo
  4. React useCallback
  5. React useLayoutEffect
  6. React useDebugValue

Let’s understand certain additional Hooks in the following sections.

1. React useRef

What is useRef in react hook?

useRef in react hook is part of the React Hooks API. It is a function that takes a maximum of one argument and returns an Object. 

The returned object has a property called current whose value is the argument passed to useRef. If you invoke it without an argument, the returned object’s current property is set to undefine. 

Syntax:

The code following explains how to invoke the useRef hook in functional components.

const myRef = React.useRef(null);

React useRef Hook returns a mutable ref object, where the current property is initialized to the passed argument (initialValue). We can apply it as below:

Example:

import { useRef } from 'react'
  const refContainer = useRef(initialValue)

Use: The useRef Hook in react is used here to deal with references to elements and components in React. We can here  set a reference bypassing the ref prop to an element or a component, as below:

<ComponentName ref={refContainer} />

2. React useReducer

This useReducer in react Hook is optional to useState hook and works exactly in the Redux library. We can use the useReducer hook as below:

Example:

import { useReducer } from 'react'
  const [ state, dispatch ] = useReducer(reducer, initialArg, init)

Use: The useReducer Hook is used here to deal with complicated state logic.

3. React useMemo

Memoization is an optimization technique where the result of a function call is cached and is then returned when the same input occurs again. The useMemo in react allows us to compute a value and memorize it. We can use it as follows:

Example:

import { useMemo } from 'react'
  const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b])

Use: The useMemo Hook is useful for optimization when we want to avoid re-executing expensive operations.

4. useCallback

useCallback Hook in react allows us to pass an inline callback function, and also an array of dependencies that will return a memoized version of the callback function. We can apply it as follows:

Example:

import { useCallback } from 'react'
  const memoizedCallback = useCallback(
      () => {
          doSomething(a, b)
      },
      [a, b] )

Use:  The useCallback Hook in react is useful when passing callbacks to optimized child components. It works similarly to the useMemo Hook, only for callback functions.

5. React useLayoutEffect

useLayoutEffect Hook in react is exactly to useEffect, but it only fires after all Document Object Model (DOM) mutations. We can use it as below:

Example:

import { useLayoutEffect } from 'react'
  useLayoutEffect(didUpdate)

Use:  The useLayoutEffect Hook in react can be used to read information from the DOM.

It is good practice to use the useEffect Hook whenever possible because the useLayoutEffect hook in react will block visual updates and slow down your application.

6. React useDebugValue

useDebugValue Hook in react can be used to display a label in React DevTools while creating custom Hooks. We can use it as below:

Example:

import { useDebugValue } from 'react'
  useDebugValue(value)

Use: Make sure to use the react useDebugValue Hook in custom Hooks to display the current state of your Hooks and for easier debugging purposes.

React Lifecycle Hooks

React Lifecycle hooks – The react-hookedup library offers numerous Hooks including all life cycle listeners for React.

Please keep in mind, it is not recommended to think in terms of a component life cycle when developing with Hooks. These Hooks just offer a quick way to refactor existing components to Hooks. However, when developing new components, it is recommended that you think about data flow and dependencies, rather than life cycles.

Here, we listed two of them, but the library offers many more Hooks, We can use the Hooks provided by react-hookedup as below:

React Lifecycle Hooks Example:

import { useOnMount, useOnUnmount } from 'react-hookedup'
  useOnMount(() => { ... })
  useOnUnmount(() => { ... })

Use: As from above, we can say Hooks can directly replace life cycle methods in class components

React Timer Hooks

React Timer Hooks – The react-hookedup library also offers Hooks for setInterval and setTimeout. These work similarly to calling setTimeout or setInterval directly, but as a React Hook, which will persist between re-renders. 

If we directly defined timers in our function component without Hooks, we would be resetting the timer every time the component re-renders. We can pass the time in milliseconds as a second argument. We can use them as below:

React Timer Hook Example:

import { useInterval, useTimeout } from 'react-hookedup'
  useInterval(() => { ... }, 1000)
  useTimeout(() => { ... }, 1000)

Use:  As we can see, Hooks greatly simplify how we deal with intervals and timeouts in React

React Navigation Hooks

React Navigation Hooks are part of the Navi library and are used to implement routing via Hooks in React. The Navi Library offers several other routing-related Hooks.

React Navigation Hook Example:

import { useCurrentRoute, useNavigation } from 'react-navi'
  const { views, url, data, status } = useCurrentRoute()
  const { navigate } = useNavigation()

Use:  Navigation Hooks make routing much more easygoing for use.

Other Community React Hooks

React useInput():

React useInput() Hook is used to easily implement input handling, and to synchronize the state of an input field with a variable. It can be used as below:

React useInput() Hook Example:

import { useInput } from 'react-hookedup'
  function App () {
      const { value, onChange } = useInput('')    
      return <input value={value} onChange={onChange} />
  }

Use:  Hooks greatly simplify dealing with input fields in React.

React useResource():

React useResource() Hook can be used to implement asynchronous data loading through requests in react applications. The below example shows the use.

React useResource() Hook Example:

import { useRequest } from 'react-request-hook'
  const [profile, getProfile] = useResource(id => ({
      url: `/user/${id}`,
      method: 'GET'
  })

Use: Using a special Hook for dealing with fetching data is quite simple

Custom Hook in React:

A custom hook is just a normal function that uses other hooks. If you don’t use any hooks in your function, it’s just a function, not a hook.

Rules of Custom Hook in React:

By Naming convention, the name of a hook function should start with “use”.

Problem Definition:

We want to know the offset when the user scrolls down in the browser. 

The idea is that each time the body of the document is scrolled, the hook will fire and return the current scroll offset. This could be useful in such cases where you need to move a component on the page or change it in some way in response to scrolling.

Custom Hook in React Example:

In this example, we are going to create a custom hook “useBodyScrollPosition” in react to get details of offset when the browser is scrolled down or top

We’ll call our hook useBodyScrollPosition in react.

// use-body-scroll-position.js
  import { useState, useEffect } from 'react';

export default () => { const [scrollPosition, setScrollPosition] = useState(null); useEffect(() => { const handleScroll = () => setScrollPosition(window.scrollY); document.addEventListener('scroll', handleScroll); return () => document.removeEventListener('scroll', handleScroll); }, []); return scrollPosition; }

In the below example, it does is put the scroll value in the middle of the window, updating as you vertically scroll. 

Custom Hook in React Example:

import React from 'react';
  import useBodyScrollPosition from './use-body-scroll-position';

export default () => { const scrollPosition = useBodyScrollPosition(); const wrapperStyles = { height: '4000px', }; const displayStyles = { position: 'fixed', width: '100%', top: '50%', transform: 'translateY(-50%)', fontSize: '20px', textAlign: 'center', } return ( <div style={wrapperStyles}> <div style={displayStyles}> {scrollPosition !== null ? scrollPosition : 0} </div> </div> ) }

F.A.Q (Frequently Asked Questions)

Follow more in details in F.A.Q in react documentation

  1. What are hooks in Reactjs?

Hooks are introduced in the React 16.8 version. Hooks are the functions that “hook into” React state and lifecycle features from function components. It permits you to use state and other React features without writing a class. 

  1. Why do we use hooks in react?

What are Hooks: “Hooks are a new addition to React in version 16.8 that allows you state and other React features like lifecycle methods without writing a class.”. Hooks let you always use functions instead of having to constantly switch between classes, functions, higher-order components, and render props.

  1. How do you pass props in react hooks?

Passing props to state using useState Hooks

4. How to use Hook in react?

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t operate inside classes — they let you use React without classes. (We don’t recommend rewriting your existing components overnight but you can begin using Hooks in the new ones if you’d like.)

Conclusion

Well, we covered many topics like what is the hook, hook types – basic hooks, additional hooks, Lifecycle Hooks, Timer Hooks, Navigation Hooks, Other Community Hooks, rules of hooks with examples, and many more.

If you want to explore more in-depth about hooks, follow the hook in React documentation.

Last but not least, feedback is good practice if you have read an article. Please comment and share your feedback, love to hear.


Have questions? Let's talk! Contact us now .


Share Blog

+

YEARS EXPERIENCE

+

CLIENTTELE ACROSS THE GLOBE

+

OVERALL PROJECTS

+

YEARS OF PARTNERSHIP LENGTH

+

Countries served

Subscribe to newsletter

I would like to subscribe to your newsletter to stay up-to-date with your latest news , promotions and events

Blue-Background-Image
Reach Out Image

REACH OUT

Ready to Build Something Great ?

Experience. Expertise. Know-How
80+

Tech Experts

13+

Years Of Developing

90%

Referral Business

mail-image
mail-image
mail-image