×

React Hooks

React Hooks

The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes.

Hooks are backward-compatible, which means that they do not contain any breaking changes. It does not replace the knowledge of your react concepts.

When Hooks are required?

Before using hooks, if you were writing a function component, and then you require to add some state into it, then you could only perform it by converting it into the class.

Rules of using Hooks

The Hooks are the functions of JavaScript, but we have to follow the following two rules when using them:

  • Only Call Hooks are at the Top level

It is to be noted that don’t call the hooks within the loops, conditions, or the nested functions. Always use the hooks at the top level of the react function. By using this rule, you ensure that hooks called in the same order each time a component renders.

  • Only Call Hooks from the React functions

Don’t call the hooks from the regular functions of JavaScript. Instead it, you can:

  • Call the hooks from the React function components.
  • Call the hooks from the custom hooks.

By using this rule, you can ensure that all of the stateful logic of the component is visible by its source code.

Pre-requisites of using Hooks

Some pre-requisites are necessary for using the Hooks:

  • Node version 6 or above.
  • NPM version 5.2 or above.
  • Create-react-app tool for running.

Installation of React Hooks

For using hooks, you have to run the following commands in your command prompt:

npm install react@16.8.0-alpha.1 --save 

Installation of React Hooks

npm install react-dom@16.8.0-alpha.1 --save

you have to run the following commands in your command prompt

The above commands are for installing the latest versions of React and React-DOM alpha, which support the react hooks.

Now, open your package.json file and ensure that it has the React and React-DOM dependencies that are given below:

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

Hooks State

It is the new way of declaring a state in the react app. Hooks uses the useState() functional component to retrieve and set the state. Let us try to understand it by using the following example:

App.js

import React, { useState } from 'react'; 
function App() { 
// Declare a new state variable, which we'll call "count" 
const [count, updateCount] = useState(0); 
return (

You clicked {count} times

); } export default App;

Output:

When the code gets run, you will get the following output:

When the code gets run

After the clicking of the button, the output will be:

Hooks State

In the above example, useState is the hook that requires to be called within the function for adding some local state into it. The useState returns the pair in which the first element is the initial value/current state value, and the second one is a function that allows you to update it. The useState is similar to this.setState in the class.

The code without using Hooks are given below:

App.js

import React, { useState } from 'react'; 
class App extends React.Component { 
constructor(props) { 
super(props); 
this.state = { 
count: 0 
}; 
} 
render() {  
return ( 

You clicked {this.state.count} times

); } } export default App;

Output:

code without using Hooks
code without using Hooks

Hooks Effect

It allows you to perform the side effects within the function components. It does not require the methods of the component lifecycle that are available in the class components. You can say that Hooks are similar to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.

The side effects have the common features which the most web apps are required to perform, such as:

  • Updating the DOM,
  • Fetching and Consuming the data from the server API,
  • Setting up a subscription, etc.

You can understand the Hooks effects by using the following example:

App.js

import React, { useState, useEffect } from 'react'; 
function App() { 
const [count, updateCount] = useState(0); 
// Similar to componentDidMount and componentDidUpdate: 
useEffect(() => { 
// Update the document title using the browser API 
document.title = `You clicked ${count} times`; 
}); 
return ( 

You clicked {count} times

); } export default App;

Output:

The output of the above program is the same as the previous programs.

Hooks Effect
Hooks Effect

The React component includes two types of side effects:

  • Effects without Cleanup.
  • Effects with Cleanup.

Effects without Cleanup

It is used in useEffect, and it does not block the browser from updating the screen. It makes the application more responsive. The examples of the effects that don’t require the Cleanup includes the Network requests, Manual DOM Mutations, and logging.

Effects with Cleanup

Some of the effects require the Cleanup, but some effects do not require it. For example, suppose if we need to set up the subscription for some external data sources. So, in this case, we have to Cleanup by which we prevent the leakage of memory.

Custom Hooks

A custom hook is a function of JavaScript, and its name starts with the ‘use’ which may result from calling the other hooks. The custom hook does not include any particular signature. We have to decide what it should take as an argument and what it should be returned.

It is like a normal function, and its name always starts with the ‘use’ by which you can apply the rules of the hook to it. Creating the custom hooks allows you to extract the component logic into the reusable functions.

Let us try to understand the Custom hooks by using the following example:

import React, { useState, useEffect } from 'react'; 
const useCustom = title => { 
useEffect(() => { 
document.title = title; 
}, [title]) 
} 
function App() { 
const [count, updateCount] = useState(0); 
const incrementCount = () => updateCount(count + 1); 
useCustom(`You clicked ${count} times`); 
// useEffect(() => { 
// document.title = `You clicked ${count} times` 
// }); 
return ( 

You clicked {count} times

) } export default App;

In the above code, the useCustom is a custom hook that takes the argument as a string of text. Inside the hook, we are calling the useEffect hook and set the title until the title has changed.

Built-in Hooks

React has the concept of the Built-in hook-like useState and useEffect. The useState is called within the function component for adding the local state to it, which will preserve in between the re-renders. The useState generally returns a pair, which includes the value of the current state and the function, which lets you update it. 

The Built-in hooks are divided into two parts that are as follows:

  1. Basic Hooks

The basic hooks include the following:

  • useState
  • useEffect
  • useContext

2. Additional Hooks

It includes:

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

Related Topics

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

3 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.

React Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.

React Table

React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

2 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

React Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 minutes read.

Difference Between State and Props in React

Comparison between State and Props State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over...

2 minutes read.

React Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 minutes read.

React Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

React Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 minutes read.