Hooks In ReactJS

Hooks are the functions introduced in the React 16.8 version, in order to allow the use of state and other React features without writing a class, but does not replace the knowledge of React concepts. It does not work inside classes, but, “hook into” React state and lifecycle features from function components. They do not contain any breaking changes as they are backwards-compatible.

Rules:

These rules of using Hooks are to ensure that all the stateful logic in a component is visible in its source code.

  • Do not call Hooks inside loops, conditions, or nested functions, but only at the top level of the React functions in order to ensure that Hooks are called in the same order each time a components renders.
  • Hooks cannot be called from regular JavaScript functions but can be called from React function components and from custom Hooks.

Pre-requisites:

  • Node version 6 or above
  • NPM version 5.2 or above
  • Create-react-app tool for running the React App

React Hooks Installation:
To install the latest React, run the below command in terminal:
Command:

$ npm install [email protected] --save  

To install the latest React-DOM, run the below command in terminal:
Command:

$ npm install [email protected] --save  

Ensure that the package.json file lists the React and React-DOM dependencies.

"react": "^16.8.0-alpha.1",  
"react-dom": "^16.8.0-alpha.1",

Example: Example of Hook Effect.

import React, { useState, useEffect } from 'react';  
function Counting() {  
const [i, setCount] = useState(0);  
useEffect(() => {  
document.title = `Number of click: ${i}`;  
});    
return (  
<div>  
<h3>Number of click: {i} </h3>  
<button onClick={() => setCount(i + 1)}>  
Click to Count  
</button>  
</div>  
);  
}  
export default Counting;

Output:

Explanation:
Here a new feature is added; the document title is set to a custom message, including the number of clicks.

Types of Side Effects:
There are two types of side effects.
Effects without Cleanup:
It is used in useEffect to make the app more responsive.
Example: manual DOM mutations, Network requests, Logging, etc.
Effects with Cleanup:
These are the effects that require clean up after the DOM update. Example: if we want to set up a subscription to some external data source. Cleanup of memory is done in React when the component unmounts, along with the cleaning up of the effects from the previous render before running the effects next time.

Custom Hooks:
It is a JavaScript function, which starts with “use” which can call other Hooks and is used to extract component logic into reusable functions.

Example: Example of Custom Hooks.

import React, { useState, useEffect } from 'react';  
const useDocumentTitle = title => {  
useEffect(() => {  
document.title = title;  
}, [title])  
}  
function Counting() {  
  const [i, setCount] = useState(0);  
  const incrementCount = () => setCount(i + 1);  
  useDocumentTitle(`Number of click: ${i}`);  
  return (  
    <div>  
   <h3>Number of click: {i} </h3>  
      <button onClick={incrementCount}>Click to Count</button>  
    </div>  
  )  
}  
export default Counting;

Explanation:
Here, useDocumentTitle is a custom Hook inside which useEffect Hook is called. It takes an argument as a string of text which is a title. The check and update of the title are performed only when its local state is different than what we are passing in, by the second argument of the useDocumentTitle Hook.

Built-in Hooks:

The built-in Hooks can be divided into two parts.

Basic Hooks:

There are three types of Basic built-in Hooks in ReactJS.

  • useState Hook
  • useEffect Hook
  • useContext Hook

Additional Hooks:

There are seven types of Advanced built-in Hooks in ReactJS.

  • useReducer Hook
  • useCallback Hook
  • useMemo Hook
  • useRef Hook
  • useImperativeHandle Hook
  • useLayoutEffect Hook
  • useDebugValue Hook

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