DEV Community

Cover image for Supercharge Your React Apps with Custom Hooks
Babar Bilal
Babar Bilal

Posted on • Edited on

Supercharge Your React Apps with Custom Hooks

React is a powerful library for building user interfaces, but managing state, handling side effects, and optimizing performance can quickly become complex. To simplify these challenges, I created react-custom-hooks-utils, a library of reusable React custom hooks that streamline development.

🚀 Introducing react-custom-hooks-utils

This library offers a collection of hooks designed to improve state management, handle side effects, and enhance user interactions efficiently.

📦 Installation

You can install the library using npm or yarn:

Using npm

npm install react-custom-hooks-utils
Enter fullscreen mode Exit fullscreen mode

Using yarn

yarn add react-custom-hooks-utils
Enter fullscreen mode Exit fullscreen mode

🔥 Featured Hooks & Usage

1. Fetch Data from an API (useFetch)

import { useFetch } from 'react-custom-hooks-utils';
const { data, loading, error } = useFetch('https://api.example.com/data');
Enter fullscreen mode Exit fullscreen mode
  • data: Stores the API response.
  • loading: Boolean indicating if the request is in progress.
  • error: Captures any error that occurs during the fetch.

2. Persist State in Local Storage (useLocalStorage)

import { useLocalStorage } from 'react-custom-hooks-utils';
const [name, setName] = useLocalStorage('name', 'John Doe');
Enter fullscreen mode Exit fullscreen mode
  • Retrieves and stores values in localStorage.
  • Automatically updates when values change.

3. Toggle Boolean State (useToggle)

import { useToggle } from 'react-custom-hooks-utils';
const [isVisible, toggleVisibility] = useToggle(false);
Enter fullscreen mode Exit fullscreen mode
  • Allows toggling between true and false states.

4. Debounce a Value (useDebounce)

import { useDebounce } from 'react-custom-hooks-utils';
const debouncedSearchTerm = useDebounce(searchTerm, 500);
Enter fullscreen mode Exit fullscreen mode
  • Delays updating the state until after a specified time (500ms).
  • Useful for optimizing API requests when users type in a search bar.

5. Get Window Dimensions (useWindowSize)

import { useWindowSize } from 'react-custom-hooks-utils';
const { width, height } = useWindowSize();
Enter fullscreen mode Exit fullscreen mode
  • Provides real-time updates of the window size (width and height).

6. Get Previous State (usePrevious)

import { usePrevious } from 'react-custom-hooks-utils';
const previousCount = usePrevious(count);
Enter fullscreen mode Exit fullscreen mode
  • Stores the previous state value.
  • Useful for tracking state changes over time.

7. Detect Clicks Outside an Element (useClickOutside)

import { useClickOutside } from 'react-custom-hooks-utils';
import { useRef } from 'react';
const ref = useRef();
useClickOutside(ref, () => console.log('Clicked outside!'));
Enter fullscreen mode Exit fullscreen mode
  • Detects clicks outside a referenced element.
  • Useful for closing dropdowns, modals, or sidebars when clicking outside.

8. Detect Hover State (useHover)

import { useHover } from 'react-custom-hooks-utils';
const [hoverRef, isHovered] = useHover();
Enter fullscreen mode Exit fullscreen mode
  • hoverRef: Attach this to an element.
  • isHovered: Boolean indicating if the element is being hovered.

9. Execute Code After Delay (useTimeout)

import { useTimeout } from 'react-custom-hooks-utils';
useTimeout(() => console.log('Timeout!'), 1000);
Enter fullscreen mode Exit fullscreen mode
  • Runs a callback function after a specified delay (1000ms).

10. Render Lists Easily (Each)

import { Each } from 'react-custom-hooks-utils';
const data = ['Item 1', 'Item 2', 'Item 3'];
<Each of={data} render={(item, index) => <p key={index}>{item}</p>} />
Enter fullscreen mode Exit fullscreen mode
  • Simplifies rendering lists.
  • Ensures correct key assignment and child element handling.

11. Manage Form State (useForm)

import { useForm } from 'react-custom-hooks-utils';
const { values, errors, handleChange, handleSubmit } = useForm(
  { email: '', password: '' },
  (values) => {
    const errors = {};
    if (!values.email) errors.email = 'Email is required';
    if (!values.password) errors.password = 'Password is required';
    return errors;
  }
);
Enter fullscreen mode Exit fullscreen mode
  • values: Stores form field values.
  • errors: Stores validation errors.
  • handleChange: Updates state on input change.
  • handleSubmit: Validates and submits form data.

12. Access and Track Geolocation (useGeoLocation)

import { useGeoLocation } from 'react-custom-hooks-utils';
const { loading, coordinates, error, isWatching } = useGeoLocation(
  { enableHighAccuracy: true, timeout: 5000 },
  true
);
Enter fullscreen mode Exit fullscreen mode
  • loading: Whether the location is still being fetched.
  • coordinates: The current coordinates (if available).
  • error: An error object if the location request fails.
  • isWatching: Whether the hook is currently watching for location changes.

13. Update Document Title (useDocumentTitle)

import { useDocumentTitle } from 'react-custom-hooks-utils';
const PageComponent = () => {
  useDocumentTitle('My Page Title', true);
  return <div>Content of the page</div>;
};
Enter fullscreen mode Exit fullscreen mode
  • title: The title you want to set for the document.
  • revertOnUnmount: If true, the document title will revert to its previous value when the component unmounts.

🔗 Get Started Today!

These hooks are designed to enhance productivity and simplify React development. Explore the full library on GitHub:

👉 GitHub: https://github.com/babarbilal56
👉 LinkedIn: www.linkedin.com/in/babarbilal56

⭐ Don't forget to star the repo and share your feedback!

Happy coding! 🚀

Top comments (0)