Create Basic React Hooks Application for Fetching List

    Apr 16, 2020       by Suraj Roy
react-hooks-simple-listing-app.jpg

React Hooks are a new feature added with React 16.8. It lets us use state and other class-based component features without using Class. I have already posted an article to create a basic app of CRUD with React using Hooks and now in this article, I will create a basic application for fetching a simple list using API in React Hooks application.

For showing listing, We will use JSONplaceholder API which provides dummy data.

 

Let's Get started

Create basic React app

I assume react is already installed in the system. Now run below command to create a new react application.

npx create-react-app react-hooks-basic-app

 

After running above command default react app installed on the system, now move to the project folder where we will write code inside App.js file.

 

Use Hooks in App Component

After adding Hooks to the app component, the App.js file will look like below:

 

 
import React,{ useState } from 'react';
import './App.css';
 
function App() {
const [users,setUsers] = useState([]);
const [loading, setLoading] = useState(false);
 
 
return (
<div className="App">
{loading?(
<div>Loading User List...</div>
) : (users.map((user)=>(
<div class="row">
<div class="col-md-4 offset-md-4">
<table class="table table-dark">
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.email}</td>
</tr>
</table>
</div>
</div>
 
)))}
</div>
);
}
 
export default App;
 

 

At the top, We have defined 2 state variables using Hooks(useState) for storing the fetched user list and for showing the loader when API request is in process. Below that template has been set for rendering the user list when fetched from the third party server.

 

Fetch User List from the third party server

With Hooks, useEffect is used to using the different life cycles(fetching data on page load)

 

 
import React,{useState, useEffect} from 'react';
import axios from 'axios';

........

........

// fetch data from server
useEffect(() => {
setLoading(true);
axios.get(`https://jsonplaceholder.typicode.com/users`).then((res)=>{
setUsers(res.data);
setLoading(false);
}).catch(err=>{
console.log(`something went wrong : ${err}`);
})
}, [])
 
 

 

For fetching the user list from the server. At first, loading is set to true. Axios is used to fetch the data and data is handled with promise. 

Note: Bootstrap CSS framework is used in this app so add bootstrap 4 CDN URL in index.html inside the public folder.

 

Optimize the performance

For optimizing the performance, we can use another Hook, useRef. It prevents fetching data from the server when the component is unmounted.

The main purpose of this hook is to run the code with useEffect only when the component is mounted to the view. Final code inside the App component will look like below

 

 
import React,{useState, useEffect, useRef} from 'react';
import './App.css';
import axios from 'axios';
 
function App() {
const [users,setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const isComponentMounted = useRef(true);
 
// fetch data from server
useEffect(() => {
setLoading(true);
axios.get(`https://jsonplaceholder.typicode.com/users`).then((res)=>{
setUsers(res.data);
setLoading(false);
}).catch(err=>{
console.log(`something went wrong : ${err}`);
})
return () => {
isComponentMounted.current = false;
};
}, [])
return (
<div className="App">
{loading?(
<div>Loading...</div>
) : (users.map((user)=>(
<div class="row">
<div class="col-md-4 offset-md-4">
<table class="table table-dark">
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.email}</td>
</tr>
</table>
</div>
</div>
 
)))}
</div>
);
}
 
export default App;
 

 

Now if you run the app using npm start and check the application on the browser, It should look like below.

 

 

listing image

 

Conclusion

We just created a basic React hooks application where we used basic hooks for the task. Click on the link, if you want more detail knowledge about the React Hooks

You can also find other demos of React.js Sample Projects here to start working on enterprise-level applications.

That’s all for now. Thank you for reading and I hope this demo will be very helpful for understanding basics about React with Hooks.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thanks!

You can download complete code from here. Download Code


WHAT'S NEW

Find other similar Articles here: