DEV Community

Elozino Ovedhe
Elozino Ovedhe

Posted on

React Custom Hooks

Objectives

  1. What are React Custom Hooks

  2. Functions of React Custom Hooks

  3. How to Create React Custom Hooks

  4. How to use React Custom Hooks

React Custom Hooks are created to help developers eliminate the need to write repetitive codes. It makes the development process cleaner and faster.

As a React developer, you must have heard of the word hooks, in simple terms, hooks are functions that do something for us. There are varieties of hooks but sometimes we find out that we end up repeating the same codes and this is what hooks solve.

It is also worth knowing that a key feature of React is its re-usability and hooks are no exception.

To create a custom hook, there are some things we need to note.

  1. They follow react hooks rule

  2. They use existing hook

  3. They have the "use" in front of the hook name as a convention to make developers know it is a custom hook

  4. They are like a regular react component

Now, let's dive into the code aspects.

First, we need to create a new React project. So open your terminal and type

yarn create vite
Enter fullscreen mode Exit fullscreen mode

Then select React as your template then follow the prompt. Once the installation is complete, enter the project directory (folder). To do so, type

cd nameOfProject
Enter fullscreen mode Exit fullscreen mode

Then to open the project in a code editor like VSCode, type

code.
Enter fullscreen mode Exit fullscreen mode

Congratulations!!! You have just successfully completed the first round

In your src folder create a folder name hooks and create a file name useFetch.js and paste the following code.

import { useEffect, useState } from "react";

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

  useEffect(() => {
    if (url) {
      setLoading(true);
      fetch(url)
        .then((response) => response.json())
        .then((data) => {
          setData(data);
          setLoading(false);
        })
        .catch((error) => {
          setError(error);
        });
    } else {
      setError("Please pass url as an argument");
    }
  }, [url]);

  return [data, loading, error];
};

export default useFetch;
Enter fullscreen mode Exit fullscreen mode

Explanation

We are creating a hook to help us fetch data and show us its loading state and error.

First, we create a state with react useState to hold the data, loading, and error state. Since we want to fetch data on the initial render, we use the react built-in useEffect and pass a dependency so it only runs when the dependency changes. In our case, it is the URL.

Remember the URL needs to be dynamic hence, we need to pass it as a prop in the useFetch component. Then we write our code in the useEffect code block.

  1. We are checking to see if there is a URL. if none we update the state of the error.

  2. if there is a URL, we set the loading to true.

  3. We fetch our data using fetch or axios.

  4. After fetching the data, we update the data and set the loading state to false.

  5. We also set the error to the error message from the API should the be an error during the fetch request.

  6. We return the data in an array format.

Now let's use the custom hook we just created. In our App.js file, paste the following.

import useFetch from "./hooks/useFetch";
import "./styles.css";

export default function App() {
  const url = "https://jsonplaceholder.typicode.com/posts";
  const [data, loading, error] = useFetch(url);
  return (
    <div className="App">
      <h1>Power of React Custom Hook</h1>
      {loading && <p>Loading data...</p>}
      {error && <p>{error}</p>}
      {data && (
        <div>
          {data.map((item, index) => (
            <p key={index}>{item.title}</p>
          ))}
        </div>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. We create a react component

  2. We import our custom hook

  3. We pass our URL into our custom hook as an argument

  4. We destructure out the value we sent from the useFetch hook

  5. We use it where needed

Vuala!!! Congratulations, you now know how to create and use a custom hook.

Reference code: react-custom-hook

Top comments (0)