DEV Community

Cover image for Building a Custom React Hook for Data Fetching: A Practical Guide
Ashutosh Kumar
Ashutosh Kumar

Posted on

Building a Custom React Hook for Data Fetching: A Practical Guide

React hooks have been around for a little while now, but they're still an incredibly powerful tool for reusing stateful logic in your React components. And if you're really feeling adventurous, you can even create your very own custom hooks!

With custom hooks, you can turn those pesky repetitive patterns into a super-cool function that you can use over and over again in all your different components. It's like having a secret weapon in your coding arsenal!

One common use case for custom hooks is data fetching, and in this tutorial, we're going to create a custom hook that uses the JSONPlaceholder API to fetch some data and display it in our application. With this custom hook, you'll be able to fetch data with ease, and even better, you can reuse it across different components in your app. So grab your coding hat and let's get started!

Step 1: Create React App

Alrighty then, let's get this React party started! To create a new React app, you'll want to pop open your terminal and run this little command:

npx create-react-app custom-hook
Enter fullscreen mode Exit fullscreen mode

This will create a new React app in a directory called custom-hook. Once the installation is complete, navigate to the new directory by running:

cd custom-hook
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the hook file

Create a useDataFetching.js file in the src folder of your project to match the required folder structure. After navigating to the src folder in a code editor or terminal, create the file and verify that the folder structure of your project is correct.

custom-hook/
  README.md
  node_modules/
  package.json
  src/
    App.js
    useDataFetching.js
    components/
Enter fullscreen mode Exit fullscreen mode

Step 3: Code

Custom hooks are essentially just functions that follow a specific naming convention, where the name of the function starts with the prefix use. This naming convention is important, because it tells React that the function is a hook, and it can be used with the useState, useEffect, and other built-in hooks.

We will be using the useState hook to define state variables for error, loading, and data. These three state variables, that contain essential information about the API call. The first variable indicates whether the API call was successful or not. The second variable lets the component know if the data is still loading or if it's already available. The third variable contains the actual data that the component needs to render. In a nutshell, this hook acts as a helper function that simplifies API call handling and enables components to easily access and utilize the data they need.

import { useState } from 'react';

function useDataFetching(url) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  return { data, error, loading };
}

export default useDataFetching;
Enter fullscreen mode Exit fullscreen mode

To fetch data from the API when the component mounts, we utilise the useEffect hook. Since this hook runs asynchronously, we need to mark the function as async and utilise await to handle the response. By doing so, we ensure that the response is properly handled before continuing with the rest of the code.

import { useState, useEffect } from 'react';

function useDataFetching(url) {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(url);
        const json = await response.json();
        setData(json);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, [url]);

  return { data, error, loading };
}

export default useDataFetching;
Enter fullscreen mode Exit fullscreen mode

Step 4: Utilise the Custom Hook

Now that we've created our custom hook, let's use it in our application.

Open the App.js file and replace the default content with the following code:

import useDataFetching from './useDataFetching';

function App() {
  const { data, error, loading } = useDataFetching(
    'https://jsonplaceholder.typicode.com/posts'
  );

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      {data.map(post => (
        <div key={post.id}>
          <h3>{post.title}</h3>
          <p>{post.body}</p>
        </div>
      ))}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

To see your custom hook in action just execute the following command

npm run start
Enter fullscreen mode Exit fullscreen mode

In this tutorial, we took a stroll through the park of custom React hooks for data fetching. Using this hook is like having a magical wand that can help eliminate code redundancy and enhance the recyclability of your code. I also showed you how to use the hook in a simple example component. And just like how you can teach an old dog new tricks, you can learn to create custom hooks that can simplify your React development journey! So don't be afraid to experiment and create your own hooks - who knows, you might just discover a new hack to make your code more efficient and your React skills more wizardly!

And as always
Thanks for Reading!!!

Top comments (2)

Collapse
 
thesanketsharma profile image
SANKET SHARMA

Nicely explained

Collapse
 
raxraj profile image
Ashutosh Kumar

Thank ya!!