Fetch Data With React Hooks

Fetch Data With React Hooks


Functional component and hooks are now the trending feature of react and it provides an elegant way to do things that we have been doing with class Component's with amount of code. Let's crate a reusable hook that's only job will be to fetch data and it will take only one argument which is url .

Project Creation

Let's create a project with npx create-react-app

create a file name hooks.js inside of our /src/ folder.

useFetch hook

import {useState, useEffect} from 'react';

function useFetchAPI(url) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await fetch(url);
    const json = await response.json();

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

  return [data, loading];

export {useFetchAPI}

Photo Component

Create a component called Photo.jsx inside of /src/ folder

import React from "react";
import { useFetchAPI } from "./hooks";
function Photo() {
  const [data, loading] = useFetchAPI(
  return (
      {loading ? (
      ) : (
          {data.map(({ id, title, url }) => (
            <li key={`${id}`}>
              <img alt={title} src={url} />
export default Photo;


Now if we connect our Photo component we would see the output. fetch_api_using_hook!


Hope this helps to understand hooks a bit more. See you in next post.

Moshiour Rahman
Sr. Software Engineer @ Innovative Solutions

My interests include enterprise software development, robotics, mobile computing and programmable matter.

comments powered by Disqus