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! πŸš€

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay