npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-hook-toolkit

v3.0.1

Published

Ultimate package for React developers, offering a powerful collection of hooks and components to enhance their development experience.

Readme

react-hook-toolkit package offers a comprehensive set of hooks to simplify React development. It includes hooks for managing state, handling API requests, optimizing performance, and improving user interactions. Key features include data fetching, form handling, local storage management, debouncing/throttling, window size tracking, event listeners, and more. These hooks are designed to enhance productivity by providing reusable, easy-to-use solutions for common tasks.

Note : This lightweight and type-safe package is written in TypeScript and offers full support for all hooks across all modern browsers.

Installation

Install the package:

npm install react-hook-toolkit
# or
pnpm add react-hook-toolkit

Authors

NPM   npm   npm   NPM   NPM Unpacked Size

Browser Support

| Firefox | Chrome | Safari | Opera | Edge | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |

Features

Here's the properly structured documentation with clear purpose explanations:

------------------------------------------ Custom Hooks ------------------------------------------------

📌 useBrowser
Provides comprehensive browser control and environment detection with a unified API for navigation, window management, and system interactions.

const {
    goBack,
    goForward,
    reload,
    navigateTo,
    clearBrowserData,
    historyState,
    isOnline,
    copyCurrentUrl,
    openNewTab,
    isFullscreen,
    isShareSupported,
    closeCurrentTab
  } = useBrowser();

📌 useRouter Keeps track of the current URL path and query parameters, and allows navigation by updating the browser URL. Useful for lightweight routing in apps without full routing libraries.

const { pathname, searchParams, navigate } = useRouter();

console.log(pathname); // "/dashboard"

console.log(searchParams.get("tab")); // "home"

navigate("/dashboard?tab=home");

📌 useNavigationState Combines the functionality of useRouter and React Router’s useNavigate + useLocation. Tracks pathname, searchParams, and state (from pushState), and allows navigation while passing custom state.

const { pathname, searchParams, state, navigate } = useNavigationState();

console.log(pathname); // "/dashboard"

console.log(searchParams.get("tab")); // "home"

console.log(state?.id); // 34

navigate("/dashboard", { state: { id: 34 } });

📌 useRequest
Provides an easy way to fetch data with hooks, managing loading, data, and error states.

const { data, loading, error } = useRequest('/api/data');

📌 useRequestRetry
Performs an HTTP request with retry logic, retrying a specified number of times upon failure before returning an error.

const { data, loading, error } = useRequestRetry('/api/user', { method: 'GET' }, 3);

📌 useAsync
Handles the state of an asynchronous function, including loading, success, and error states, with the ability to trigger the execution of the async operation.

const { execute, status, value, error } = useAsync(fetchUser);

execute(); // ➝ runs the async function

📌 useDebounce
Delays updating the state until after a specified delay, useful for preventing frequent updates (e.g., handling user input).

const debouncedSearch = useDebounce(searchText, 500);

📌 useDebouncedCallback
Delays the execution of a callback function until after a specified delay, resetting the delay on each call to prevent frequent execution.

const debounced = useDebouncedCallback(() => search(input), 300);

input.onChange = debounced;

📌 useDebouncedValue
Returns a debounced version of a value.

const debouncedValue = useDebouncedValue(value, 300);

📌 useThrottle
Limits how often a value updates within a given time interval, useful for performance optimization.

const throttledScroll = useThrottle(scrollValue, 300);

📌 useDelay
Delays the update of a value for a specified amount of time before reflecting it in the state.

const delayedValue = useDelay(value, 500);

📌 useTimer
Starts a countdown timer that updates the time every second, returning the current time and any errors.

const { time, error } = useTimer(60); // starts from 60 and counts down

📌 useInterval
Runs a callback function at a specified time interval and clears it when the delay is null or the component unmounts.

useInterval(() => {
  console.log('Tick');
}, 1000);

📌 useTimeout
Executes a function after a specified delay and cleans up automatically when dependencies change.

useTimeout(() => {
  console.log('Time\'s up!');
}, 2000);

📌 useForm
Manages form state, handles input changes, and performs validation using provided validators.

const { values, errors, handleChange, validate } = useForm({ name: '', email: '' });

handleChange('name', 'John');

validate({
  name: (val) => (!val ? 'Required' : null),
  email: (val) => (!val.includes('@') ? 'Invalid email' : null),
});

📌 useFormSubmit
Handles form submission with loading/error states and success callbacks.

const { submit, isLoading, error } = useFormSubmit(apiCall, {
  onSuccess: (data) => console.log('Saved!', data)
});

// Example
submit(formData);

📌 useSmartForm
Complete form management with validation, submission, and state handling.

const { register, handleSubmit, errors } = useSmartForm({
  initialValues,
  validationSchema,
  onSubmit: (data) => console.log(data)
});

// Example
<input {...register('email') />
<button onClick={handleSubmit}>Save</button>

📌 useCrossFieldValidation
Handles complex validation rules that depend on multiple fields.

const { errors, validate } = useCrossFieldValidation({
  rules: {
    password: (val, { confirmPassword }) => val === confirmPassword,
  },
  initialValues
});

// Example
validate('password', 'secret123', { confirmPassword: 'secret123' });

📌 useFieldArray
Manages dynamic arrays of form fields with add/remove/reorder operations.

const { fields, append, remove, move } = useFieldArray(initialItems);

// Example
append({ name: '', email: '' });
remove(0); // Remove first item
move(1, 0); // Move second item to first position

📌 useFormWizard
Manages multi-step forms with navigation between steps.

const { currentStep, next, prev, goto } = useFormWizard(steps.length);

// Example
next(); // Move to next step
goto(3); // Jump to step 4

📌 usePersistedForm
Automatically persists form state to localStorage/sessionStorage and restores it on page reload.

const { values, setField, reset } = usePersistedForm('form-key', initialValues);

// Example
setField('username', 'john_doe'); // Auto-saves to storage
reset(); // Clears storage

📌 useEventListener
Listens for a specified event on an element or window, and triggers the handler function when the event is fired. It ensures proper cleanup when the component is unmounted.

useEventListener('resize', (e) => {
  console.log('Window resized');
});

📌 useEventListeners
Simplifies adding/removing event listeners.

useEventListeners({
  click: handleClick,
  resize: handleResize
});

// Example
useEventListeners({
  keydown: (e) => console.log(e.key)
});

📌 useKeyPress
Detects whether a specific key is being pressed or released.

const isEnterPressed = useKeyPress('Enter');

📌 useLongPress
Detects long press gestures.

const handlers = useLongPress(() => console.log('Long pressed!'), {
  threshold: 1000
});

// Example
<button {...handlers}>Hold me</button>

📌 useTouch
Tracks touch events on a given DOM element, returning the touch positions for touchstart, touchmove, and touchend.

const ref = useRef(null);
const {
  touchStart,
  touchMove,
  touchEnd
} = useTouch(ref);

<div ref={ref}>Swipe here</div>

📌 useIdle
Detects when user becomes inactive.

const isIdle = useIdle(30000); // 30s timeout

// Example
{isIdle && <ScreenSaver />}

📌 useDragReorder
Enables drag-and-drop reordering of lists.

const { items, dragStart, dragOver, drop } = useDragReorder(initialItems);

// Example
<div 
  draggable 
  onDragStart={() => dragStart(index)}
  onDragOver={() => dragOver(index)}
  onDrop={drop}
/>

📌 useToggle
A simple boolean toggle hook that returns a state and a function to toggle its value.

const [isOpen, toggle] = useToggle(false);

📌 useArray Provides an array state with helper functions to manipulate it, including setting, adding, removing by index, and clearing elements.

const { array, set, push, removeByIndex, clear } = useArray([1, 2, 3]);

push(4);            // ➝ [1, 2, 3, 4]
removeByIndex(1);   // ➝ [1, 3, 4]
clear();            // ➝ []

📌 useStepper
Manages step-based navigation by keeping track of the current step index and providing functions to move forward, backward, and reset.

const { activeStep, handleNext, handleBack, handleReset, isFirstStep, isLastStep } = useStepper(5);

handleNext(); // ➝ advances step
handleBack(); // ➝ goes back
handleReset(); // ➝ step 0

📌 useDrawer Provides global drawer state and controls to open/close the drawer and manage the current selected main menu, including support for button-triggered toggling.

const {
  drawerOpen,              
  openDrawer,              
  closeDrawer,            
  openDrawerInButton,      
  closeDrawerInButton,     
  currentMainMenu,
  setCurrentMainMenu,  
} = useContext();

📌 useUndo
Provides undo/redo functionality for state changes.

const { state, setState, undo, redo } = useUndo(initialState);

// Example
setState({ items: [...] });
undo(); // Reverts to previous state

📌 useGenericReducer
A custom reducer function that takes an initialState and an object of actions, returning a new state based on the action type.

const reducer = useGenericReducer(initialState, {
  increment: (state) => ({ count: state.count + 1 }),
});
const [state, dispatch] = useReducer(reducer, initialState);

📌 useIsMounted
Tracks whether the component is mounted or unmounted, returning a boolean value indicating the component's mount status.

const isMounted = useIsMounted();

📌 useIsFirstRender
Returns true only on component's first render.

const isFirst = useIsFirstRender();

// Example
useEffect(() => {
  if (!isFirst) console.log('Updated!');
}, [deps]);

📌 usePrevious
Tracks the previous value of a state or prop.

const previousValue = usePrevious(currentValue);

📌 useUpdateEffect
Executes a side effect on updates after the initial render, skipping the effect during the first render to avoid unnecessary executions.

useUpdateEffect(() => {
  console.log("This runs only on updates.");
}, [value]);

📌 useList
Manages array state with utility methods.

const { list, push, remove, update } = useList(initialItems);

// Example
push(newItem);
remove(0); // Remove first item

📌 useLocalStorage
A hook to persist state in localStorage. It initializes state from localStorage and updates it whenever the value changes.

const [token, setToken] = useLocalStorage('authToken', '');

📌 useSessionStorage
Stores and retrieves data from the sessionStorage API, persisting the data during the session. It provides a getter and setter for session-based data.

const [value, setValue] = useSessionStorage("myKey", "default");

setValue("newValue");
console.log(value);

📌 useCookie
Manages cookies by providing functions to get, set, and delete a specific cookie by its key.

const [token, setToken, deleteToken] = useCookie('token');

setToken('abc123');
deleteToken();

📌 usePersistedState
Stores and retrieves state from localStorage to persist data across page reloads.

const [theme, setTheme] = usePersistedState('theme', 'light');

📌 useHistory
Provides methods to navigate the browser history, including pushing and replacing history states, as well as moving back and forward in the history stack.

const {
  history,
  state,
  push,
  replace,
  goBack,
  goForward
} = useHistory();

push('/about', { from: 'home' });
replace('/profile');
goBack();
goForward();

📌 useRecentSearch
Return and manage recent searched history.

  const { recentSearches, addSearch, clearSearch, hasSearch } = useRecentSearch<SearchItem>({
    key: 'myRecentItems',
    limit: 5,
    uniqueKey: 'id',
    excludeEmpty: true,
  });

📌 useHistoryState
Manages state history with undo/redo capabilities.

const { state, setState, undo, redo } = useHistoryState(initialState);

// Example
setState({...});
undo(); // Reverts change

📌 useVisibilityChange
Tracks the visibility state of the document and returns whether the page is currently visible or hidden.

const isVisible = useVisibilityChange(); // ➝ true | false

📌 useDarkMode
Detects and manages dark mode preferences in the browser.

const [isDarkMode, toggleDarkMode] = useDarkMode();

📌 usePreferredLanguage
Detects the preferred language set in the browser.

const language = usePreferredLanguage();

📌 useIndexedDB
Provides a hook to interact with IndexedDB in the browser, enabling persistent client-side storage.

const { data, setData } = useIndexedDB('dbName');

📌 useMediaQuery
Checks if a media query condition matches the current viewport, useful for responsive design.

const isMobile = useMediaQuery('(max-width: 768px)');

📌 useWindowSize
Returns the current window size (width and height).

const { width, height } = useWindowSize();

📌 useResizeObserver
Observes and returns the dimensions of an HTML element using the ResizeObserver API.

const size = useResizeObserver(ref);

// size = { width: 200, height: 100 }

📌 useScrollPosition
Tracks the horizontal (x) and vertical (y) scroll positions of the window.

const { x, y } = useScrollPosition();

📌 useScrollDirection
Determines whether the user is scrolling up or down based on window scroll position changes.

const direction = useScrollDirection(); // ➝ 'up' | 'down'

📌 useScrollLock
Locks or unlocks scrolling on the page.

useScrollLock(true); // Lock scrolling
useScrollLock(false); // Unlock scrolling

📌 useLockBodyScroll
Prevents scrolling on the body element, useful for modals or off-canvas menus.

useLockBodyScroll(true);

📌 useCss
Allows injecting dynamic CSS rules into the document.

useCss('.class { color: red; }');

📌 useReducedMotion
Detects whether the user has reduced motion settings in their OS preferences.

const prefersReducedMotion = useReducedMotion();

📌 useImageLoader
Provides a way to load and display images in a way that improves performance and loading behavior.

const { isLoading, image } = useImageLoader('imageURL');

📌 useBattery
Monitors the battery status of the device, including level, charging status, and remaining charging or discharging time.

const { level, charging, supported, loading, chargingTime, dischargingTime } = useBattery();

📌 useGeoLocation
Retrieves the user's current geographic location and returns it along with any error encountered.

const { position, error } = useGeoLocation();

📌 useMousePosition
Tracks the user's mouse position in real-time and returns the coordinates.

const { x, y } = useMousePosition();

📌 useOnlineStatus
Monitors the user's network connection status (online/offline).

const isOnline = useOnlineStatus();

📌 useSound
Controls the playback of an audio file, including play, pause, and stop functionalities, while also managing the audio volume and handling any errors.

const {
  play,
  pause,
  stop,
  setVolume,
  isPlaying,
  error
} = useSound("/sound.mp3");

play();
pause();
stop();
setVolume(0.5);

📌 useSpeak
Converts text to speech using the Web Speech API, allowing the text to be spoken and handling errors.

const { speak, error } = useSpeak('Hello world!');
speak();

📌 usePermission

Monitors the status of a specific browser permission (like geolocation, camera, microphone, etc.) and updates reactively when the permission state changes.

const permission = usePermission({ name: 'geolocation' });

📌 usePageLeave

Detects when the mouse leaves the viewport (commonly used to detect exit intent on websites).

usePageLeave(() => {
  console.log('Mouse left the page');
});

📌 useMotion

Subscribes to device motion events (like acceleration or rotation) and returns the latest motion values from sensors on mobile devices.

const motion = useMotion();
console.log(motion.acceleration);

📌 useHoverDirty

Returns true when the mouse is hovering over a target element. Unlike useHover, this doesn't handle delays or complex state logic—just raw hover state.

const ref = useRef(null);
const isHovered = useHoverDirty(ref);

📌 useBeforeUnload

Prompts the user with a confirmation dialog before leaving the page (refresh, close tab, etc.).

useBeforeUnload(true); // Triggers default browser dialog

📌 useClickAway

Triggers a handler function when a user clicks outside of a specified element.

const ref = useRef(null);
useClickAway(ref, () => {
  console.log('Clicked outside');
});

📌 useResponsive

Tracks screen size and returns breakpoint-based flags (xs, sm, md, etc.) to help in building responsive UI layouts.

const screens = useResponsive();
console.log(screens.md); // true or false

📌 useUnmountedRef

Returns a ref that indicates whether the component is currently unmounted—useful to prevent state updates on unmounted components.

const unmountedRef = useUnmountedRef();

📌 useCountUp
Animates a counter that counts up from 0 to a target value within a specified duration, returning the current count and any errors.

const { count, error } = useCountUp(100, 5000); // counts up to 100 in 5s

📌 useCountDown
Counts down from a specified start value to zero, updating every second and returning the current count and any errors.

const { count, error } = useCountDown(10); // counts down from 10

📌 useWebSocket
Manages WebSocket connections with auto-reconnect.

const { send, message, status } = useWebSocket('ws://api.example.com');

// Example
send(JSON.stringify({ action: 'ping' }));

License

MIT © (2022-2024)