How to Create a React Custom Hook

Updated 2 weeks ago admin Javascript / React

React hooks are functions that we can reuse, and we can also create our custom hooks if we have code that we want to reuse in multiple components.

Create a custom hook

Let's assume that we have two components: the first creates and the second updates a post, and each post belongs to a category, so we need to fetch categories in each component. To do that, we can create a custom hook that fetches categories, and we reuse it in both components. 

const useCategories = async () => {
    try {
        const response = await axios.get(`/api/categories`);
        return response.data;
    } catch (error) {
        console.log(error);
    }
}

export default useCategories;

Use the custom hook

You can use the custom hook in your components like this:

import React, { useEffect, useState } from "react";
import useCategories from "../../custom/useCategories";

export default function Create() {
    const [category_id, setCategoryId] = useState(""); 
    const [categories, setCategories] = useState([]); 

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

    const fetchCategories = async () => {
      const fetchedCategories = await useCategories();
      setCategories(fetchedCategories);
    }

    return (
      <div className="row my-5">
        <div className="col-md-6 mx-auto">
          <div className="card">
            <div className="card-body">
                <form className="mt-5">
                    <div className="mb-3">
                        <label htmlFor="category_id" className="form-label">Category*</label>
                        <select 
                            name="category_id" 
                            onChange={(e) => setCategoryId(e.target.value)}
                            value={category_id}
                            className="form-select">
                        <option value="" disabled>Choose a category</option>
                        {
                            categories?.map(category => (
                            <option key={category.id} value={category.id}>{category.name}</option>
                            ))
                        }
                        </select>
                    </div>
                </form>
            </div>
          </div>
        </div>
      </div>
    )
}