DEV Community

Cover image for Custom Hooks made easy :)
Deepak Sharma
Deepak Sharma

Posted on

Custom Hooks made easy :)

Custom Hooks in React: A Beginner's Guide

Custom hooks in React can sometimes seem like an advanced topic, intimidating beginners with their complexity. However, once you grasp the fundamentals, you'll find that custom hooks are an incredibly powerful tool that can simplify your code and enhance reusability. In this article, we'll break down custom hooks into simple, digestible pieces, demystifying their concept and empowering you to leverage them effectively in your React applications. Whether you're just starting your journey with React or looking to deepen your understanding, by the end of this guide, you'll feel confident in creating and using custom hooks in your projects. Let's dive in!

What Are Custom Hooks?
Custom hooks are simply functions that encapsulate common logic or behavior in your application. They follow the naming convention of starting with the word "use," making them recognizable as hooks.

const useMyHook = () => { /* your logic */ }
Enter fullscreen mode Exit fullscreen mode

Why Custom Hooks?
Custom hooks empower you to abstract away repetitive code into reusable functions, promoting a modular and scalable architecture for your React applications.

But how do they work, and how can you create your own? Let's explore further.
Sure, let's create examples of two common custom hooks: useToggle and useFetch

1. useToggle Hook:

The useToggle hook is useful for managing boolean state toggles in your components.

import { useState } from 'react';

const useToggle = (initialState = false) => {
  const [state, setState] = useState(initialState);

  const toggle = () => {
    setState((prevState) => !prevState);
  };

  return [state, toggle];
};

// Usage example:
// const [isOpen, toggleOpen] = useToggle(false);
Enter fullscreen mode Exit fullscreen mode

You can use it in your component like this:

const MyComponent = () => {
  const [isOpen, toggleOpen] = useToggle(false);

  return (
    <div>
      <button onClick={toggleOpen}>
        {isOpen ? 'Close' : 'Open'} Menu
      </button>
      {isOpen && (
        <ul>
          <li>Menu Item 1</li>
          <li>Menu Item 2</li>
          <li>Menu Item 3</li>
        </ul>
      )}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

This hook simplifies managing boolean state toggles, such as opening and closing modals, collapsible sections, or toggling visibility of elements.

2. useFetch Hook:

The useFetch hook simplifies data fetching in React components. It handles fetching data from an API endpoint and manages loading and error states.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const result = await response.json();
        setData(result);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();

    return () => {
      // Cleanup function to cancel fetch on unmount or on re-fetch
    };
  }, [url]);

  return { data, loading, error };
};

// Usage example:
// const { data, loading, error } = useFetch('https://api.example.com/data');
Enter fullscreen mode Exit fullscreen mode
const MyComponent = () => {
  const { data, loading, error } = useFetch(`https://api.example.com/data?search=${debouncedSearchTerm}`);

  // Render your component based on data, loading, and error states
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we've explored the concept of custom hooks in React and how they can simplify your code and enhance reusability. We started by understanding what custom hooks are and why they're valuable in React development. We then delved into creating practical examples of custom hooks, including useToggle and useFetch.

As you continue your journey with React, consider exploring more custom hooks. A great resource for discovering additional hooks is usehooks-ts where you can find a variety of pre-made hooks for different use cases.

With practice, you'll become more comfortable leveraging custom hooks to build powerful and efficient React applications. Happy coding!

Happy coding!

Top comments (0)