DEV Community

Cover image for Reusable Code: React Custom Hooks Guide
Nahidul Fahim
Nahidul Fahim

Posted on

Reusable Code: React Custom Hooks Guide

React's functional components have gained significant popularity due to the introduction of hooks, which allow developers to manage state and side effects more efficiently. One powerful feature is the ability to create custom hooks, enabling the reuse of logic across different components. In this article, I’ll explain the concept of custom hooks in React and guide you through the process of creating them. First, if you are new, let’s get introduced to React Hooks. What are they and why are they?

Unveiling the Essence of Hooks

  • Hooks, introduced in React 16.8, are functions that allow us to "hook into" React features without writing a full class component.
  • They provide access to state, side effects, context, and other React features without the need for class lifecycle methods.
  • Common built-in hooks include useState, useEffect, useContext, useMemo, useReducer, and more.

When should we consider custom hooks?

As mentioned earlier, custom hooks are JavaScript functions that utilize one or more of the existing hooks, allowing you to encapsulate and reuse logic across components. They follow a naming convention: starting with use helps identify them as hooks.

  • Shared Logic: If we find ourselves replicating logic across multiple components, a custom hook can encapsulate that logic for reuse.
  • Component Complexity: When a component becomes complex with state management and side effects, a custom hook can enhance the clarity and organization of our codebase.
  • State Management: Custom hooks empower us to create custom state management solutions tailored to our specific needs.

Crafting the first custom hook

Imagine we have this situation: our application needs to use the logged-in user's data in multiple places. Instead of fetching this data from the database in every component separately, we can make our lives easier. That's where custom hooks come in handy.

Think of it as our assistant. We tell it once to get the user data, and then we can call on it from any component whenever we need that information. It's like saying, "Hey assistant, give me the user data," and it takes care of the rest. This way, we don't have to repeat the same fetching process in every nook and cranny of our application. It's a smart way of saying, "Do it once, use it everywhere."

Let’s go through the processes:

1. Name: Start your hook function name with use to indicate its purpose. In our case, we are naming it, “useUserData”
2. Logic: To fetch data, we need Axios (or you can use fetch), useEffect and useState to store data, error and loading state.

import { useState, useEffect } from 'react';
import axios from 'axios'; // if you don't have Axios installed in your project, first install it

const useUserData = () => {

    // let’s take a dummy email
    const email = "dummy@email.com";

    // get necessary react hooks
    const [isLoading, setIsLoading] = useState(false);
    const [currentUserData, seCurrentUserData] = useState(null);
    const [error, setError] = useState(null);

    // URL
    const url = 'dummy URL' // use your own URL

    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true);
            try {
                const response = await axios.get(url); // Use Axios to make the GET request
                const data = response.data; // Axios automatically parses JSON responses
                seCurrentUserData(data);
            } catch (error) {
                setError(error);
            } finally {
                setIsLoading(false);
            }
        };
        fetchData();
    }, [url]);


    return { isLoading, currentUserData, error }
};
export default useUserData;

Enter fullscreen mode Exit fullscreen mode

3. Use the custom hook in components: Now we are ready to use the custom hook in our component wherever it is needed.

import useUserData from './useUserData'; // your own path to import


const MyComponent = () => {


    // get the custom hook
    const { isLoading, currentUserData, error } = useUserData();

    // conditional loading for loading state
    if (isLoading) {
        return <p>Loading...</p>;
    }
    // if there is any error
    if (error) {
        return <p>Error: {error.message}</p>;
    }

    // Imagine this is the dummy data in 'currentUserData'
/*
{
    "id": 123,
    "name": "John Doe",
    "email": "john.doe@example.com",
    "birthDate": "1990-01-01",
    "imageURL": "https://example.com/john_doe.jpg",
    "role": "user"
  }
*/

    return (
        <div>
            <h1>Data from API</h1>
            <p>{currentUserData?.name}</p>
        </div>
    );
};


export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these steps, we can successfully create and integrate a custom hook into your React application. By mastering custom hooks, we unlock a powerful way to structure our React applications. This approach encourages us to reuse code, facilitating easier maintenance and ensuring a clear distinction between different aspects of our application.

Follow me on: LinkedIn

Top comments (0)