Author -  Sai gowtham

How to Fetch Data using React hooks

In this tutorial, we will learn about how to make the ajax requests in functional components by creating our own custom react hook.

React hooks are JavaScript functions which help us to use react features in functional components.

If you don’t know about react hooks then check out previous tutorial

useFetch custom react hook

Let’s create our own custom hook called useFetch which helps us to fetch the data from the API.

We are using useState and useEffect hooks to add the state and lifecycle methods in functional components.

useState: It is used to add the state in functional components.

useEffect: It helps us to use the lifecycle features in functional components like componentDidMount,componentDidUpdate,componentUnmount.

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

const useFetch = url => {
  const [data, setData] = useState(null);
  async function fetchData() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);  }

  useEffect(() => {fetchData()},[url]);  return data;
};

In the above code first, we imported useState and useEffect hooks from the ‘react’ library.

useState hook takes one argument which is initial state and returns back an array with two values currentState and a function which is used to update the state.

By default useEffect hooks runs on every time when a component is updated but we only need to fetch the data when a component initially Mounts to the dom, to stop this behavior in useEffect we passed the second argument an empty array [].

Let’s use our useFetch hook to make an API request.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const useFetch = url => {
  const [data, setData] = useState(null);

  async function fetchData() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
  }

  useEffect(() => {fetchData()},[url]);

  return data;
};

function App() {

  const data = useFetch("https://jsonplaceholder.typicode.com/todos/1");
  if (!data) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        <li>{data.id}</li>
        <li>{data.title}</li>
      </ul>
    )
  }
}

export default App;

In <App> component we invoked useFetch hook by passing an URL and it returns back the data.It takes some time to get the data from the API so that we display the loading state if the data is not available.

Once the data is available we display the actual data.

Let’s add the loading state to the useEffect hook instead of we manually checking if data is available or not.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const useFetch = url => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  async function fetchData() {
    const response = await fetch(url);
    const json = await response.json();
    setData(json);
    setLoading(false)  }

  useEffect(() => {
    fetchData()
  }, []);

  return {loading,data};
};

function App() {

  const {loading,data} = useFetch("https://jsonplaceholder.typicode.com/todos/1");
  return (
    <div>
      {loading ? <div>Loading...</div> :
      <ul>
       <li>{data.id}</li>
       <li>{data.title}</li>
      </ul>
      }
    </div>
  )
}

export default App;

react-hooks-fetch-data

You can also check FetchData component

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY