Loading, please wait...

A to Z Full Forms and Acronyms

What is React Hooks and It's Benefits?

In this article, we will discuss about what is React Hooks?

Introduction

React Hooks are the function that lets you “hook into” React state and lifecycle features from function components. It allows using React state and other features without using a class, which means it does not work inside classes. Hooks are backward-compatible which means there is no breaking change and it doesn’t affect your knowledge on React. It uses when we write function components and realize you need to add some state on it. Previously it is done by using a class but now hooks give offers to do this in the current component. Hooks bring functional components that are used with classes but using built-in hooks like useState, useEffect, and useContext able to work. There are also some hooks such as useReducer, useCallback, useMemo, useRef, etc.

The feature is added newly in React 16.8 version. React Native also supports Hooks since the release of the React Native 0.59 version.

Why the React Hooks?

According to ReactJS official, there is some reason/ motivation behind the use of React Hooks:

  • Reusing logic between components is troublesome:

With Hooks, you can reuse logic between your components without changing their design or structure.

  • Complex parts can be hard to comprehend:

At the point when components become bigger and do numerous activities, it gets hard to comprehend over the long haul. With the help of Hooks, by separating a specific single component into different littler functions dependent on what bits of this isolated components are connected.

  • Classes are very befuddling:

Classes are prevention to learning React appropriately; you would need to see how this in JavaScript functions which varies from a different language. Respond Hooks tackles this issue by permitting developers to use the best of React highlights without using classes.

Benefits of React Hooks

There are the following benefits for the developer as:

  • Improved code reuse,
  • Better code synthesis,
  • Better defaults,
  • Sharing non-visual logic with the utilization of custom Hooks,
  • Adaptability in going here and there the component tree.

 Rules of Hooks

Likewise, JavaScript Hooks are similar to them but it follows rules during the use which ensures that all logic in components is visible in source code or not.

  • Only call Hooks at the top level:

You have to use Hooks always at the Top-level because this rule ensures that Hooks are called in the same order each time in a component render. So, don’t call Hooks inside loops, condition, or nested condition.

  • Only call Hooks from React Functions:

You can call Hooks from the function instead of any other JavaScript function. You can also call hooks from using custom hooks.

React Hooks provide a linter plugin library to enforce these rules automatically. To install these runs on command prompt:

npm install eslint-plugin-react-hooks  --save-dev

Built-in Hooks

We describe the APIs for the built-in Hooks in React, which can be divided into two parts:

  1. Basic Hooks
  • useState
  • useEffect
  • useContext
  1. Additional Hooks
  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

useState(): Hook state is used for declaring the state in the React. useState() is a Hook that allows the developer to manipulate, update the state inside the component without converting it to the class component. It returns a pair od two-variable i.e. one is current state value and the other one is the function that lets for updation. You can call the function using event handler or else, it is similar to this.setState in a class but it didn’t combine old and new components.

import React, { useState } from 'react';
function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

You can also use the State Hook more than once in the single component.

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

They also use the object destructuring and array destructuring in the State Hook.

Object Destructuring requires more efforts for getting a variable and renaming it. The first variable is the first item in the array. Whereas, in Array Destructuring, it gives two variables and you can also name it again whatever you want. Where one variable is the Value and the second variable is a function to update the value. The useState argument is the initial state value and its counter starts with 0 always.

useEffect(): The Effect Hook, useEffect, adds the capacity to perform side effects from a function component. It fills a similar need as componentDidMount, componentDidUpdate, and component will unmount in React classes, yet brought together into a single API.

Side effects have some common features which perform according to the application needs, such as:

  • Fetching data
  • Manually changing the DOM (document title)
  • Setting up a subscription
import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

At the point when you call useEffect, you're advising React to run your "impact" work after flushing changes to the DOM. Impacts are proclaimed inside the part so they approach its props and state.

Effects without Cleanup- It doesn’t block the browser from updating the screen as it becomes responsive. Eg- DOM mutation, Network requests, etc.

Effect With Cleanup- It requires cleanup after DOM updation. React plays out the cleanup of memory when the components unmount. In any case, as we realize that, effect runs for each render technique and not simply once. Thusly, React additionally clean up effect from the past render before running the effect next time.

useContext(): The useContext() hook accepts a context object, i.e the value that is returned from React.createContext, and then it returns the current context value for that context.

When the closest <MyContext.Provider> over the component refreshes, this Hook will trigger a rerender with the most recent setting esteem went to that MyContext supplier. Regardless of whether an ancestor uses React.memo or shouldComponentUpdate, a rerender will at present happen to begin at the part itself use useContext such as:

  • Correct: useContext(MyContext)
  • Incorrect:useContext(MyContext.Consumer)
  • Incorrect:useContext(MyContext.Provider)
const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);  return (    <button style={{ background: theme.background, color: theme.foreground }}>      I am styled by theme context!    </button>  );
}

Custom Hooks

A custom Hook is a JavaScript work. The name of custom Hook begins with "use" which can call different Hooks. A custom Hook is much the same as a regular function, and "use" first and foremost tells that this function follows the rule of Hooks. Building custom Hooks permits you to extricate component logic into reusable functions. A custom Hook is a convention which naturally follows from the design of Hooks, instead of a React feature. Eg:

import React, { useState, useEffect } from 'react';  
  
const useDocumentTitle = title => {  
  useEffect(() => {  
    document.title = title;  
  }, [title])  
}  
  
function CustomCounter() {  
  const [count, setCount] = useState(0);  
  const incrementCount = () => setCount(count + 1);  
  useDocumentTitle(`You clicked ${count} times`);  
  // useEffect(() => {  
  //   document.title = `You clicked ${count} times`  
  // });  
  
  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={incrementCount}>Click me</button>  
    </div>  
  )  
}  
export default CustomCounter;  

Inside this Hook, we call useEffect Hook and set the title as long as the title has changed. The subsequent contention will play out that check and update the title just when its nearby state is not the same as what we are going in.

A to Z Full Forms and Acronyms