Top Related Projects
React Hooks — 👍
Awesome React Hooks
🔥 A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥
A collection of useful React hooks
👩🍳 A list of React Hooks utility library containing popular customized hooks
Quick Overview
Rooks is a collection of React hooks designed to enhance and simplify React development. It provides a wide range of reusable hooks for common functionalities, allowing developers to easily add features like debounce, throttle, geolocation, and more to their React applications.
Pros
- Large collection of ready-to-use hooks for various purposes
- Well-documented with examples and TypeScript support
- Actively maintained with regular updates
- Modular structure allows for importing only needed hooks
Cons
- Some hooks may have a learning curve for beginners
- Potential overhead if importing the entire library instead of individual hooks
- Dependency on React limits its use to React-based projects
- Some hooks may have simpler alternatives built into React or other popular libraries
Code Examples
- Using the
useInterval
hook for recurring tasks:
import { useInterval } from "rooks";
function Counter() {
const [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000);
return <div>Count: {count}</div>;
}
- Implementing debounce with
useDebounce
:
import { useDebounce } from "rooks";
function SearchComponent() {
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearch = useDebounce(performSearch, 300);
function handleInputChange(e) {
setSearchTerm(e.target.value);
debouncedSearch(e.target.value);
}
return <input value={searchTerm} onChange={handleInputChange} />;
}
- Using
useGeolocation
to get user's location:
import { useGeolocation } from "rooks";
function LocationDisplay() {
const geoObj = useGeolocation();
if (geoObj.isError) {
return <div>Error: {geoObj.message}</div>;
}
return (
<div>
Latitude: {geoObj.lat}, Longitude: {geoObj.lng}
</div>
);
}
Getting Started
To start using Rooks in your React project:
-
Install the package:
npm install rooks
-
Import and use hooks in your components:
import { useInterval, useDebounce } from "rooks"; function MyComponent() { // Use the hooks here }
-
Refer to the Rooks documentation for detailed usage instructions and examples for each hook.
Competitor Comparisons
React Hooks — 👍
Pros of react-use
- Larger collection of hooks (100+) compared to rooks (~60)
- More frequent updates and active maintenance
- Wider adoption and community support
Cons of react-use
- Potentially overwhelming due to the large number of hooks
- Some hooks may be less specialized or optimized compared to rooks
- Slightly larger bundle size due to the extensive collection
Code Comparison
react-use:
import { useToggle } from 'react-use';
const [isOn, toggleIsOn] = useToggle(false);
rooks:
import { useToggle } from 'rooks';
const [isOn, setIsOn] = useToggle(false);
Both libraries offer similar functionality for basic hooks like useToggle
. However, react-use tends to provide more specialized hooks for various use cases, while rooks focuses on core functionality with some unique additions.
react-use is generally more suitable for projects requiring a wide range of hooks and frequent updates, while rooks may be preferable for those seeking a more focused set of hooks with potentially better optimization for specific use cases.
Awesome React Hooks
Pros of awesome-react-hooks
- Comprehensive collection of React hooks from various sources
- Community-driven with contributions from multiple developers
- Categorized list for easy navigation and discovery
Cons of awesome-react-hooks
- Not a standalone library, just a curated list of hooks
- Requires additional effort to integrate hooks from different sources
- May include outdated or unmaintained hooks
Code Comparison
awesome-react-hooks:
- [react-use](https://github.com/streamich/react-use)
- [useHooks](https://usehooks.com/)
- [beautiful-react-hooks](https://github.com/antonioru/beautiful-react-hooks)
rooks:
import { useDidMount } from "rooks";
function App() {
useDidMount(() => {
console.log("mounted");
});
return <div>Hello World</div>;
}
Summary
awesome-react-hooks is a curated list of React hooks from various sources, offering a wide range of options for developers. It's community-driven and well-organized but requires more effort to implement as it's not a standalone library.
rooks, on the other hand, is a comprehensive collection of pre-built, ready-to-use hooks in a single package. It offers a more streamlined integration process but may have a smaller selection compared to the extensive list in awesome-react-hooks.
Choose awesome-react-hooks for exploration and flexibility, or rooks for a more cohesive, ready-to-use solution.
🔥 A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥
Pros of Beautiful React Hooks
- More focused on UI-related hooks, making it potentially more suitable for frontend-heavy applications
- Cleaner and more consistent naming conventions for hooks
- Includes some unique hooks not found in Rooks, like
useViewportSpy
anduseMediaQuery
Cons of Beautiful React Hooks
- Smaller collection of hooks compared to Rooks
- Less frequent updates and maintenance
- Lacks some utility hooks that Rooks provides, such as array and promise-related hooks
Code Comparison
Beautiful React Hooks:
import { useMediaQuery } from 'beautiful-react-hooks';
const Component = () => {
const isSmallScreen = useMediaQuery('(max-width: 768px)');
return <div>{isSmallScreen ? 'Small Screen' : 'Large Screen'}</div>;
};
Rooks:
import { useMediaMatch } from 'rooks';
const Component = () => {
const isSmallScreen = useMediaMatch('(max-width: 768px)');
return <div>{isSmallScreen ? 'Small Screen' : 'Large Screen'}</div>;
};
Both libraries offer similar functionality for media queries, with slightly different naming conventions. Rooks uses useMediaMatch
, while Beautiful React Hooks uses useMediaQuery
.
A collection of useful React hooks
Pros of react-hanger
- Simpler API with fewer hooks, making it easier to learn and use
- Focused specifically on React hooks, potentially leading to a more streamlined experience
- Lightweight package with minimal dependencies
Cons of react-hanger
- Less comprehensive set of hooks compared to rooks
- Less frequent updates and maintenance
- Smaller community and fewer contributors
Code Comparison
react-hanger:
const [value, setValue] = useInput('')
const [count, {increment, decrement}] = useCounter(0)
const [isOpen, toggle] = useBoolean(false)
rooks:
const {value, setValue} = useInput('')
const {count, increment, decrement} = useCounter(0)
const {value: isOpen, toggle} = useToggle(false)
Both libraries offer similar functionality for basic hooks, but rooks provides a more extensive set of hooks and utilities. react-hanger focuses on simplicity, while rooks aims for comprehensiveness. The choice between the two depends on the specific needs of your project and personal preferences.
👩🍳 A list of React Hooks utility library containing popular customized hooks
Pros of react-recipes
- Focuses on providing a collection of common React patterns and solutions, making it easier for developers to find and implement specific functionalities
- Includes a wider range of recipes, covering both hooks and components
- Offers more detailed explanations and usage examples for each recipe
Cons of react-recipes
- Less actively maintained compared to rooks, with fewer recent updates
- Smaller community and fewer contributors, potentially leading to slower issue resolution and feature additions
- Limited to React-specific solutions, while rooks offers some more general-purpose hooks
Code Comparison
react-recipes:
const useHover = () => {
const [isHovering, setIsHovering] = useState(false);
const handleMouseOver = () => setIsHovering(true);
const handleMouseOut = () => setIsHovering(false);
return [isHovering, { onMouseOver: handleMouseOver, onMouseOut: handleMouseOut }];
};
rooks:
const useHover = (ref) => {
const [isHovering, setIsHovering] = useState(false);
useEffect(() => {
const node = ref.current;
if (node) {
node.addEventListener("mouseenter", () => setIsHovering(true));
node.addEventListener("mouseleave", () => setIsHovering(false));
return () => {
node.removeEventListener("mouseenter", () => setIsHovering(true));
node.removeEventListener("mouseleave", () => setIsHovering(false));
};
}
}, [ref]);
return isHovering;
};
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Essential React custom hooks â to super charge your components!
List of all hooks
ð¬ Animation & Timing - 5 hooks
- useIntervalWhen - Sets an interval immediately when a condition is true
- useLockBodyScroll - This hook locks the scroll of the body element when
isLocked
is set totrue
. - useRaf - A continuously running requestAnimationFrame hook for React
- useResizeObserverRef - Resize Observer hook for React.
- useTimeoutWhen - Takes a callback and fires it when a condition is true
ð Browser APIs - 9 hooks
- useGeolocation - A hook to provide the geolocation info on client side.
- useIdleDetectionApi - Hook to detect when user is idle using Idle Detection API with polyfill
- useNavigatorLanguage - Navigator Language hook for React.
- useOnline - Online status hook for React.
- useOrientation - orientation hook for react
- useScreenDetailsApi - Hook for multi-screen information and management using Screen Details API
- useSpeech - Speech synthesis hook for React
- useVibrate - Vibration API hook for React
- useWebLocksApi - Hook for coordinating operations across tabs/workers with Web Locks API
ð ï¸ Development & Debugging - 2 hooks
- useRenderCount - Get the render count of a component
- useWhyDidYouUpdate - A hook that can track which value change caused a rerender
ð Events - 14 hooks
- useDocumentEventListener - A react hook to an event listener to the document object
- useDocumentVisibilityState - Returns the visibility state of the document.
- useFocus - Handles focus events for the immediate target element.
- useFocusWithin - Handles focus events for the target component.
- useIsDroppingFiles - Check if any files are currently being dropped anywhere. Useful for highlighting drop areas.
- useOnClickRef - Callback on click/tap events
- useOnHoverRef - On hover callback hook
- useOnLongHover - Fires a callback when an element is hovered for a while
- useOnLongPress - Fire a callback on long press
- useOnWindowResize - A React hook for adding an event listener for window resize
- useOnWindowScroll - A React hook for adding an event listener for window scroll
- useOutsideClick - Outside click(for a ref) event as hook for React.
- useOutsideClickRef - A hook that can track a click event outside a ref. Returns a callbackRef.
- useWindowEventListener - Adds an event listener to window
ð Form & File Handling - 1 hook
- useFileDropRef - Drop files easily
â¨ï¸ Keyboard & Input - 5 hooks
- useInput - Input hook for React.
- useKey - keypress, keyup and keydown event handlers as hooks for react.
- useKeyBindings - useKeyBindings can bind multiple keys to multiple callbacks and fire the callbacks on key press.
- useKeyRef - Very similar useKey but it returns a ref
- useKeys - A hook which allows to setup callbacks when a combination of keys are pressed at the same time.
ð¥ Lifecycle & Effects - 9 hooks
- useAsyncEffect - A version of useEffect that accepts an async function
- useDeepCompareEffect - Deep compare dependencies instead of shallow for useEffect
- useDidMount - componentDidMount hook for React
- useDidUpdate - componentDidUpdate hook for react
- useDocumentTitle - A hook to easily update document title with React
- useEffectOnceWhen - Runs a callback effect atmost one time when a condition becomes true
- useIsomorphicEffect - A hook that resolves to useEffect on the server and useLayoutEffect on the client.
- useLifecycleLogger - A react hook that console logs parameters as component transitions through lifecycles.
- useWillUnmount - componentWillUnmount lifecycle as hook for React.
ð±ï¸ Mouse & Touch - 3 hooks
- useMouse - Mouse position hook for React.
- useMouseMoveDelta - Tracks delta of mouse move
- useMouseWheelDelta - Tracks delta of mouse move
â¡ Performance & Optimization - 4 hooks
- useDebounce - Debounce hook for react
- useDebouncedValue - Tracks another value and gets updated in a debounced way.
- useDebounceFn - Powerful debounce function hook for React
- useThrottle - Throttle custom hook for React
âï¸ State - 18 hooks
- useArrayState - Array state manager hook for React
- useCountdown - Count down to a target timestamp and call callbacks every second (or provided peried)
- useCounter - Counter hook for React.
- useGetIsMounted - Checks if a component is mounted or not at the time. Useful for async effects
- useLocalstorageState - UseState but auto updates values to localStorage
- useMapState - A react hook to manage state in a key value pair map.
- useMultiSelectableList - A custom hook to easily select multiple values from a list
- useNativeMapState - Manage Map() object state in React
- usePreviousDifferent - usePreviousDifferent returns the last different value of a variable
- usePreviousImmediate - usePreviousImmediate returns the previous value of a variable even if it was the same or different
- usePromise - Promise management hook for react
- useQueueState - A React hook that manages state in the form of a queue
- useSafeSetState - set state but ignores if component has already unmounted
- useSelect - Select values from a list easily. List selection hook for react.
- useSelectableList - Easily select a single value from a list of values. very useful for radio buttons, select inputs etc.
- useSessionstorageState - useState but syncs with sessionstorage
- useSetState - Manage the state of a Set in React.
- useStackState - A React hook that manages state in the form of a stack
ð State History & Time Travel - 4 hooks
- useTimeTravelState - A hook that manages state which can undo and redo. A more powerful version of useUndoState hook.
- useToggle - Toggle (between booleans or custom data)hook for React.
- useUndoRedoState - Setstate but can also undo and redo
- useUndoState - Drop in replacement for useState hook but with undo functionality.
âï¸ UI - 12 hooks
- useAudio - Audio hook
- useBoundingclientrect - getBoundingClientRect hook for React.
- useBoundingclientrectRef - A hook that tracks the boundingclientrect of an element. It returns a callbackRef so that the element node if changed is easily tracked.
- useDimensionsRef - Easily grab dimensions of an element with a ref using this hook
- useFullscreen - Use full screen api for making beautiful and emersive experinces.
- useIntersectionObserverRef - A hook to register an intersection observer listener.
- useInViewRef - Simple hook that monitors element enters or leave the viewport that's using Intersection Observer API.
- useMediaMatch - Signal whether or not a media query is currently matched.
- useMutationObserver - Mutation Observer hook for React.
- useMutationObserverRef - A hook that tracks mutations of an element. It returns a callbackRef.
- usePictureInPictureApi - Hook for managing Picture-in-Picture video functionality
- useVideo - Video hook for react
ð§ Utilities & Refs - 7 hooks
- useEventListenerRef - A react hook to add an event listener to a ref
- useForkRef - A hook that can combine two refs(mutable or callbackRefs) into a single callbackRef
- useFreshCallback - Avoid stale closures and keep your callback fresh
- useFreshRef - Avoid stale state in callbacks with this hook. Auto updates values using a ref.
- useFreshTick - Like use-fresh-ref but specifically for functions
- useMergeRefs - Merges any number of refs into a single ref
- useRefElement - Helps bridge gap between callback ref and state
ð± Window & Viewport - 2 hooks
- useWindowScrollPosition - A React hook to get the scroll position of the window
- useWindowSize - Window size hook for React.
𧪠Experimental Hooks - 1 hook
- useSuspenseNavigatorUserAgentData - Suspense-enabled hook for getting high entropy values from Navigator User Agent Data API
â ï¸ Experimental hooks may be removed or significantly changed in any release without notice. Use with caution in production.
Features
â Collection of 96 hooks as standalone modules.
â Standalone package with all the hooks at one place
â ï¸ Experimental Hooks: Some hooks are marked as experimental and may be removed or significantly changed in any release without notice. Use these hooks with caution in production applications. Import experimental hooks from rooks/experimental
.
â CommonJS, UMD and ESM Support
Installation
npm i -s rooks
Import any hook from "rooks" and start using them!
import { useDidMount } from "rooks";
Usage
function App() {
useDidMount(() => {
alert("mounted");
});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Standalone Package
Package containing all the hooks is over here. - Docs and Npm Install
License
MIT
Contributors â¨
Thanks goes to these wonderful people (emoji key):
Other hooks libraries
These are some libraries that I constantly take inspiration and ideas from
Top Related Projects
React Hooks — 👍
Awesome React Hooks
🔥 A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥
A collection of useful React hooks
👩🍳 A list of React Hooks utility library containing popular customized hooks
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot