Top Related Projects
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
🐻 Bear necessities for state management in React
The official, opinionated, batteries-included toolset for efficient Redux development
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Quick Overview
React-hookz/web is a comprehensive library of React hooks designed to enhance and simplify React development. It offers a wide range of utility hooks that cover various aspects of web development, from state management to DOM manipulation and beyond.
Pros
- Extensive collection of hooks for diverse use cases
- Well-documented with clear examples and TypeScript support
- Actively maintained with regular updates and improvements
- Lightweight and modular, allowing for selective imports
Cons
- Learning curve for developers unfamiliar with advanced hook patterns
- Some hooks may overlap with existing React features or other popular libraries
- Potential for over-reliance on external hooks instead of custom solutions
- Limited community support compared to more established React libraries
Code Examples
- Using the
useBooleanhook for toggle state:
import { useBoolean } from '@react-hookz/web';
function ToggleComponent() {
const [isOn, setIsOn] = useBoolean(false);
return (
<button onClick={setIsOn.toggle}>
{isOn ? 'Turn Off' : 'Turn On'}
</button>
);
}
- Implementing a debounced input with
useDebouncedCallback:
import { useDebouncedCallback } from '@react-hookz/web';
function DebouncedSearch() {
const debouncedSearch = useDebouncedCallback(
(value) => console.log('Searching for:', value),
500
);
return (
<input
type="text"
onChange={(e) => debouncedSearch(e.target.value)}
placeholder="Search..."
/>
);
}
- Managing async state with
useAsync:
import { useAsync } from '@react-hookz/web';
function AsyncDataFetcher() {
const { error, result, loading, execute } = useAsync(
() => fetch('https://api.example.com/data').then(res => res.json())
);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (result) return <div>Data: {JSON.stringify(result)}</div>;
return <button onClick={execute}>Fetch Data</button>;
}
Getting Started
To start using react-hookz/web in your project:
-
Install the package:
npm install @react-hookz/web -
Import and use hooks in your components:
import { useBoolean, useAsync, useDebouncedCallback } from '@react-hookz/web'; function MyComponent() { // Use the hooks in your component logic const [isLoading, setIsLoading] = useBoolean(false); // ... } -
Refer to the official documentation for detailed usage instructions and available hooks.
Competitor Comparisons
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
Pros of Query
- More comprehensive data fetching and state management solution
- Extensive documentation and larger community support
- Built-in caching and background refetching capabilities
Cons of Query
- Steeper learning curve due to more complex API
- Potentially overkill for simpler applications
- Larger bundle size compared to react-hookz/web
Code Comparison
Query:
const { data, isLoading, error } = useQuery('todos', fetchTodos)
if (isLoading) return 'Loading...'
if (error) return 'An error occurred: ' + error.message
return (
<ul>{data.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>
)
react-hookz/web:
const [todos, setTodos] = useState([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState(null)
useAsync(async () => {
try {
const data = await fetchTodos()
setTodos(data)
setIsLoading(false)
} catch (err) {
setError(err)
setIsLoading(false)
}
}, [])
While Query provides a more declarative approach with built-in state management, react-hookz/web offers a simpler, more flexible solution that may be preferable for less complex data fetching scenarios.
🐻 Bear necessities for state management in React
Pros of zustand
- Simpler API with a more intuitive learning curve
- Built-in middleware support for persistence, devtools, and more
- Better performance for large-scale applications due to its minimalistic approach
Cons of zustand
- Less comprehensive set of utility hooks compared to react-hookz/web
- May require additional libraries for more complex state management scenarios
- Smaller community and ecosystem compared to react-hookz/web
Code Comparison
zustand:
import create from 'zustand'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
react-hookz/web:
import { useCounter } from '@react-hookz/web'
const [count, { increment }] = useCounter(0)
Both libraries offer simple state management solutions, but zustand provides a more centralized approach, while react-hookz/web focuses on individual hook utilities.
The official, opinionated, batteries-included toolset for efficient Redux development
Pros of Redux Toolkit
- Provides a standardized, opinionated approach to Redux state management
- Includes built-in tools for simplifying common Redux use cases (e.g., createSlice)
- Extensive documentation and large community support
Cons of Redux Toolkit
- Steeper learning curve for beginners compared to simpler hook-based solutions
- Can be overkill for small to medium-sized applications
- Requires more boilerplate code than React Hookz
Code Comparison
Redux Toolkit:
import { createSlice } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: state => state + 1,
},
})
React Hookz:
import { useCounter } from '@react-hookz/web'
const [count, { increment }] = useCounter(0)
React Hookz offers a more straightforward approach for simple state management, while Redux Toolkit provides a robust solution for complex state management in larger applications. React Hookz is easier to learn and implement for beginners, but Redux Toolkit offers more powerful features for advanced state management scenarios.
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
Pros of Query
- More comprehensive data fetching and state management solution
- Extensive documentation and larger community support
- Built-in caching and background refetching capabilities
Cons of Query
- Steeper learning curve due to more complex API
- Potentially overkill for simpler applications
- Larger bundle size compared to react-hookz/web
Code Comparison
Query:
const { data, isLoading, error } = useQuery('todos', fetchTodos)
if (isLoading) return 'Loading...'
if (error) return 'An error occurred: ' + error.message
return (
<ul>{data.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>
)
react-hookz/web:
const [todos, setTodos] = useState([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState(null)
useAsync(async () => {
try {
const data = await fetchTodos()
setTodos(data)
setIsLoading(false)
} catch (err) {
setError(err)
setIsLoading(false)
}
}, [])
While Query provides a more declarative approach with built-in state management, react-hookz/web offers a simpler, more flexible solution that may be preferable for less complex data fetching scenarios.
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Pros of Recoil
- Provides a more powerful and flexible state management solution for complex React applications
- Offers built-in support for asynchronous data fetching and derived state
- Integrates well with React's Concurrent Mode and Suspense features
Cons of Recoil
- Steeper learning curve compared to simpler hook-based solutions
- Requires additional setup and configuration
- May introduce unnecessary complexity for smaller projects or simpler state management needs
Code Comparison
Recoil:
import { atom, useRecoilState } from 'recoil';
const countState = atom({
key: 'countState',
default: 0,
});
function Counter() {
const [count, setCount] = useRecoilState(countState);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
react-hookz/web:
import { useCounter } from '@react-hookz/web';
function Counter() {
const [count, { inc }] = useCounter(0);
return <button onClick={inc}>{count}</button>;
}
The react-hookz/web example demonstrates a more straightforward approach using a custom hook, while Recoil introduces a global atom-based state management system. react-hookz/web is generally simpler for basic use cases, while Recoil offers more advanced features for complex state management scenarios.
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
@react-hookz/web is a library of general-purpose React hooks built with care and SSR compatibility
in mind.
Install
This one is pretty simple, everyone knows what to do:
npm i @react-hookz/web
# or
yarn add @react-hookz/web
As hooks was introduced to the world in React 16.8, @react-hookz/web requires - you guessed it -
react and react-dom 16.8+.
Also, as React does not support IE, @react-hookz/web don't either.
Usage
This package distributed with ESNext language level and ES modules system. It means that depending on your browser target you might need to transpile it. Every major bundler provides a way to transpile
node_modulesfully or partially. Address your bundler documentation for more details.
You can import hooks two ways:
// from the root of package
import {useMountEffect} from '@react-hookz/web';
// or single hook directly
import {useMountEffect} from '@react-hookz/web/useMountEffect/index.js';
In case your bundler supports tree-shaking (most of modern does) - both variants are equal and only necessary code will get into your bundle. Direct hook imports should be considered otherwise.
Migrating from react-use
@react-hookz/web was built as
a spiritual successor of react-use by one of
its former maintainers.
Hooks list
-
Callback
useDebouncedCallbackâ Makes passed function debounced, otherwise acts likeuseCallback.useRafCallbackâ Makes passed function to be called within next animation frame.useThrottledCallbackâ Makes passed function throttled, otherwise acts likeuseCallback.
-
Lifecycle
useConditionalEffectâ LikeuseEffectbut callback invoked only if given conditions match a given predicate.useCustomCompareEffectâ LikeuseEffectbut uses a provided comparator function to validate dependency changes.useDebouncedEffectâ LikeuseEffect, but passed function is debounced.useDeepCompareEffectâ LikeuseEffectbut uses@react-hookz/deep-equalcomparator function to validate deep dependency changes.useFirstMountStateâ Returns a boolean that istrueonly on first render.useIntervalEffectâ LikesetIntervalbut in the form of a React hook.useIsMountedâ Returns a function that yields current mount state.useIsomorphicLayoutEffectâ LikeuseLayoutEffectbut falls back touseEffectduring SSR.useMountEffectâ Run an effect only when a component mounts.useRafEffectâ LikeuseEffect, but the effect is only run within an animation frame.useRerenderâ Returns a callback that re-renders the component.useThrottledEffectâ LikeuseEffect, but the passed function is throttled.useTimeoutEffectâ LikesetTimeout, but in the form of a React hook.useUnmountEffectâ Run an effect only when a component unmounts.useUpdateEffectâ An effect hook that ignores the first render (not invoked on mount).useLifecycleLoggerâ This hook provides logging when the component mounts, updates and unmounts.
-
State
useControlledRerenderStateâ LikeuseState, but its state setter accepts an extra argument, that allows cancelling renders.useCounterâ Tracks a numeric value and offers functions for manipulating it.useDebouncedStateâ LikeuseStatebut its state setter is debounced.useFunctionalStateâ LikeuseStatebut instead of raw state, a state getter function is returned.useListâ Tracks a list and offers functions for manipulating it.useMapâ Tracks the state of aMap.useMediatedStateâ LikeuseState, but every value set is passed through a mediator function.usePreviousâ Returns the value passed to the hook on previous render.usePreviousDistinctâ Returns the most recent distinct value passed to the hook on previous renders.useQueueâ A state hook implementing FIFO queue.useRafStateâ LikeReact.useState, but state is only updated within animation frame.useRenderCountâ Tracks component's render count including first render.useSetâ Tracks the state of aSet.useToggleâ LikeuseState, but can only betrueorfalse.useThrottledStateâ LikeuseStatebut its state setter is throttled.useValidatorâ Performs validation when any of the provided dependencies change.
-
Navigator
useNetworkStateâ Tracks the state of the browser's network connection.useVibrateâ Provides vibration feedback using the Vibration API.usePermissionâ Tracks the state of a permission.
-
Miscellaneous
useSyncedRefâ LikeuseRef, but it returns an immutable ref that contains the actual value.useCustomCompareMemoâ LikeuseMemobut uses provided comparator function to validate dependency changes.useDeepCompareMemoâ LikeuseMemobut uses@react-hookz/deep-equalcomparator function to validate deep dependency changes.useHookableRefâ LikeuseRefbut it is possible to define handlers for getting and setting the value.
-
Side-effect
useAsyncâ Executes provided async function and tracks its results and errors.useAsyncAbortableâ LikeuseAsync, but also providesAbortSignalas first function argument to the async function.useCookieValueâ Manages a single cookie.useLocalStorageValueâ Manages a single LocalStorage key.useSessionStorageValueâ Manages a single SessionStorage key.
-
Sensor
useIntersectionObserverâ Observe changes in the intersection of a target element with an ancestor element or with the viewport.useMeasureâ UsesResizeObserverto track an element's dimensions and to re-render the component when they change.useMediaQueryâ Tracks the state of a CSS media query.useResizeObserverâ Invokes a callback wheneverResizeObserverdetects a change to the target's size.useScreenOrientationâ Checks if the screen is inportraitorlandscapeorientation and automatically re-renders on orientation change.useDocumentVisibilityâ Tracks document visibility state.
-
Dom
useClickOutsideâ Triggers a callback when the user clicks outside a target element.useEventListenerâ Subscribes an event listener to a target element.useKeyboardEventâ Invokes a callback when a keyboard event occurs on the chosen target.useWindowSizeâ Tracks the inner dimensions of the browser window.
Contributors
Top Related Projects
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
🐻 Bear necessities for state management in React
The official, opinionated, batteries-included toolset for efficient Redux development
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
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