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.
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.
After adding Hooks to the app component, the App.js file will look like below:
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.
With Hooks, useEffect is used to using the different life cycles(fetching data on page load)
........
........
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.
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
Now if you run the app using npm start and check the application on the browser, It should look like below.
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!