Loading, please wait...

A to Z Full Forms and Acronyms

How to use Hooks in the React Application

Jul 04, 2020 React Hooks, Hooks, React, ReactJS, 3069 Views
In this article, we'll learn about How Hooks use in the React Application

In the previous article, we discuss What is React Hooks and its Components i.e. What-is-React-Hooks-and-It's-Benefits

Now in this article, we see How Hooks use in the React application. There are some following steps:

Step 1: Create an application using create-react-app, run npm install create-react-app <project name>

and also install the library for it by running some commands such as 

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

npm install Axios 

Step 2: Firstly add useState hooks, as it is used to store the data to the component.

import React from 'react';
 
function BooksList () {
   const [books, updateBooks] = React.useState([]);
}
const handleClick = () => {
       updateBooks([...books, { name: 'A new Book', id: '...'}]);
   }
   
   return (
   <ul>
       books.map(book => (
        <li key={book.id}>{book.name}</li>  
       ));
   </ul>
   );
}

Step 3: Add Axios request that helps in HTTP service. Note that the second parameter in useEffect Hook is an empty array which shows that it will run only once. Another important point is that React declared on asyn function in your call back and immediately execute it.

function BooksList () {
   const [books, updateBooks] = React.useState([]);
 
   React.useEffect(function effectFunction() {
       async function fetchBooks() {
           const response = await fetch('https://the-fake-harry-potter-api.com/books');
           const json = await response.json();
           updateBooks(json.data);
       }
       fetchBooks();
   }, []);
   
   return (
   <ul>
       books.map(book => (
        <li key={book.id}>{book.name}</li>  
       ));
   </ul>
   );
}

By this, we can finally fetch and store the data in the application. As it is just an example to guide you to use Hooks in the React

A to Z Full Forms and Acronyms