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 [email protected] --save 

Installation of React Hooks

npm install [email protected] --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



ADVERTISEMENT
ADVERTISEMENT