Logo

dev-resources.site

for different kinds of informations.

Reusable Code: React Custom Hooks Guide

Published at
2/23/2024
Categories
webdev
react
hook
javascript
Author
nahidulislam
Categories
4 categories in total
webdev
open
react
open
hook
open
javascript
open
Author
12 person written this
nahidulislam
open
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 = "[email protected]";

    // 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": "[email protected]",
    "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

hook Article's
30 articles in total
Favicon
Share the state of a hook between components
Favicon
Understanding Hooks in the Phoenix Framework
Favicon
React Hooks: A Detailed Explanation
Favicon
Reusable React Hook Form
Favicon
Client side Git hooks 101
Favicon
React Hooks
Favicon
How not to useEffect
Favicon
Understanding useContext Hooks in React – An introduction and a Comprehensive Guide for Web Developers
Favicon
Understanding useState Hook in React – An introduction and a Comprehensive Guide for Web Developers
Favicon
Understanding useEffect Hooks in React – An introduction and Comprehensive Guide for Web Developers
Favicon
React 18 hooks
Favicon
Reusable Code: React Custom Hooks Guide
Favicon
React Usecallback for Kids/Beginners
Favicon
Optimizing Event Handlers in React using useCallback
Favicon
Understanding the useState Hook in React
Favicon
Implement refetch with axis
Favicon
Handle component state using local storage: useLocalStorage with Typescript
Favicon
Skills of writing unit test for react
Favicon
The practice of using Microsoft OAuth in the React hook
Favicon
Hooks in React
Favicon
A Guide to Building Custom Hooks in React
Favicon
A Guide to React Custom Hooks
Favicon
React Performance Booster - Introduction to the useMemo hook
Favicon
Mastering LocalStorage Management with React Hooks
Favicon
React Custom Hooks that can take props, but not always, what to do in TypeScript?
Favicon
useLocation Hook in React Router
Favicon
useLocation Hook in React Router
Favicon
Building a Custom React Hook: useIsAppOffline
Favicon
useLongPress Custom Hook
Favicon
Renderprops vs Custom Hooks: Which one to use?

Featured ones: