This library contains a collection of reusable React custom hooks to simplify state management, side effects, and user interactions.
To use these hooks in your React project, install the react-custom-hooks-utils
package via npm or yarn:
npm install react-custom-hooks-utils
yarn add react-custom-hooks-utils
Once installed, you can import and use the hooks in your React components. Below is a detailed explanation of how to use each hook:
import { useFetch } from 'react-custom-hooks-utils';
const { data, loading, error } = useFetch('https://api.example.com/data');
data
: Stores the API response.loading
: Boolean indicating if the request is in progress.error
: Captures any error that occurs during the fetch.
import { useLocalStorage } from 'react-custom-hooks-utils';
const [name, setName] = useLocalStorage('name', 'John Doe');
- Retrieves and stores values in
localStorage
. - Automatically updates when values change.
import { useToggle } from 'react-custom-hooks-utils';
const [isVisible, toggleVisibility] = useToggle(false);
- Allows toggling between
true
andfalse
states.
import { useDebounce } from 'react-custom-hooks-utils';
const debouncedSearchTerm = useDebounce(searchTerm, 500);
- Delays updating the state until after a specified time (
500ms
). - Useful for optimizing API requests when users type in a search bar.
import { useWindowSize } from 'react-custom-hooks-utils';
const { width, height } = useWindowSize();
- Provides real-time updates of the window size (
width
andheight
).
import { usePrevious } from 'react-custom-hooks-utils';
const previousCount = usePrevious(count);
- Stores the previous state value.
- Useful for tracking state changes over time.
import { useClickOutside } from 'react-custom-hooks-utils';
import { useRef } from 'react';
const ref = useRef();
useClickOutside(ref, () => console.log('Clicked outside!'));
- Detects clicks outside a referenced element.
- Useful for closing dropdowns, modals, or sidebars when clicking outside.
import { useHover } from 'react-custom-hooks-utils';
const [hoverRef, isHovered] = useHover();
hoverRef
: Attach this to an element.isHovered
: Boolean indicating if the element is being hovered.
import { useTimeout } from 'react-custom-hooks-utils';
useTimeout(() => console.log('Timeout!'), 1000);
- Runs a callback function after a specified delay (
1000ms
).
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>} />
- Simplifies rendering lists.
- Ensures correct key assignment and child element handling.
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;
}
);
values
: Stores form field values.errors
: Stores validation errors.handleChange
: Updates state on input change.handleSubmit
: Validates and submits form data.
import { useGeoLocation } from 'react-custom-hooks-utils';
const LocationComponent = () => {
// Call the hook with options (optional) and watch set to true
const { loading, coordinates, error, isWatching } = useGeoLocation(
{ enableHighAccuracy: true, timeout: 5000 }, // Optional options
true // Set to true if you want to watch for location changes
);
if (loading) {
return <div>Loading location...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<h3>Geolocation</h3>
<p>Latitude: {coordinates?.latitude}</p>
<p>Longitude: {coordinates?.longitude}</p>
<p>Watching: {isWatching ? 'Yes' : 'No'}</p>
</div>
);
};
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.
import {useDocumentTitle} from 'react-custom-hooks-utils';
const PageComponent = () => {
useDocumentTitle('My Page Title', true); // Set the title and revert on unmount
return <div>Content of the page</div>;
};
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.
A hook to manage browser cookies with React state.
import { useCookie } from 'react-custom-hooks-utils';
const [cookie, setCookie] = useCookie('theme', 'light');
key
(string) – The name of the cookie.initialValue
(any) – The default value if the cookie is not set.
cookie
– The current cookie value.setCookie(value, daysToExpire)
– Function to update the cookie value and set an expiration.
A hook to manage dark mode preferences using localStorage
and system settings.
import { useDarkMode } from 'react-custom-hooks-utils';
const [isDarkMode, toggleDarkMode] = useDarkMode();
isDarkMode
– Boolean indicating if dark mode is enabled.toggleDarkMode
– Function to toggle dark mode.
A hook to run a function at a set interval.
import { useInterval } from 'react-custom-hooks-utils';
useInterval(() => {
console.log('This runs every second');
}, 1000);
callback
– Function to execute.delay
– Interval duration in milliseconds.
A hook to detect if a specific key is being pressed.
import { useKeyPress } from 'react-custom-hooks-utils';
const isEnterPressed = useKeyPress('Enter');
targetKey
(string) – The key to listen for.
keyPressed
– Boolean indicating if the key is pressed.
A hook to check if the current screen size matches a given media query.
import { useMediaQuery } from 'react-custom-hooks-utils';
const isMobile = useMediaQuery('(max-width: 768px)');
query
(string) – CSS media query string.
matches
– Boolean indicating if the query matches.
A hook to throttle a function call, ensuring it executes at most once within a given time frame.
import { useThrottle } from 'react-custom-hooks-utils';
const throttledFunction = useThrottle(() => console.log('Throttled'), 2000);
callback
– Function to be throttled.delay
– Time in milliseconds to wait before the function can be executed again.
- A throttled version of the callback function.
This project is open-source and available under the MIT License.