Ionic + React - Custom Hook

In this page you will find the instructions to create a custom hook for your Ionic + React application. I will keep things very simple.

To start, lets start by creating an Ionic + React application. Open your terminal and send this command:

$ ionic start api_hook blank --type=react -capacitor --confirm --no-interactive
$ cd api_hook

I will be using VS Code, so open the project with VS Code:

$ code .

Add a file in the src/components/ directory. The file can be called useFetch.tsx and add the following code:


import React, { useEffectuseState } from "react";
import axios from "axios";

function useFetch(urlany) {
  const [datasetData] = useState<any>(null);
  const [loadingsetLoading] = useState(false);
  const [errorsetError] = useState(null);
  useEffect(() => {
    setLoading(true); // set loading to true
      .then((response=> {
      .catch((err=> {
      .finally(() => {
  }, [url]);

  // Function to call when button is clicked
  const refetch = () => {
    setLoading(true); // set loading to true
      .then((response=> {
      .catch((err=> {
      .finally(() => {

  return { dataloadingerrorrefetch };

export default useFetch;

Now, open the src/components/exploreContainer.tsx file and make it look like this:

import "./ExploreContainer.css";

import useFetch from "../components/useFetch";

import {
from "@ionic/react";

const ExploreContainerReact.FC = () => {
  const { datarefetch } = useFetch("");

  if (!data) {
    return <h1>Loading...</h1>;
  } else {
    return (
              <IonCardSubtitle>Category: {data?.category}</IonCardSubtitle>

            <IonButton onClick={refetch}>Refresh</IonButton>

          <div className="container">
              Ionic React Custom API Hook Example{" "}
                rel="noopener noreferrer"
                UI Components

export default ExploreContainer;

That is all the code you will need. You can now start the ionic server to look at the application to make a call to the joke api.

$ ionic serve

Hope that helps.