CodesJava

Easy learning with example program codes

Hooks in ReactJS

React Hooks

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 react@16.8.0-alpha.1 --save  

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

$ npm install react-dom@16.8.0-alpha.1 --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",

Hooks State:
Hook state is used to declare a state in React app using the useState() functional component. It is used for setting and retrieving state.

Example: Example of Hook State.
App.js:

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

Output:

Explanation:
Here, useState is the Hook which is similar to this.setState in class and returns a pair where the first element is the current state value/initial value, and the second one is a function which allows us to update it.

Hooks Effect:
To perform side effects (an action) in the function components, Hooks Effect is utilised. They are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods, as they do not use components lifecycle methods which are available in class components. Some of the important features of Side effects are updating the DOM, fetching and consuming data from a server API and setting up a subscription.

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

 

Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status