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
useBoolean
hook 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_modules
fully 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.
Coming from react-use
? Check out our
migration guide.
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
â LikeuseEffect
but callback invoked only if given conditions match a given predicate.useCustomCompareEffect
â LikeuseEffect
but uses a provided comparator function to validate dependency changes.useDebouncedEffect
â LikeuseEffect
, but passed function is debounced.useDeepCompareEffect
â LikeuseEffect
but uses@react-hookz/deep-equal
comparator function to validate deep dependency changes.useFirstMountState
â Returns a boolean that istrue
only on first render.useIntervalEffect
â LikesetInterval
but in the form of a React hook.useIsMounted
â Returns a function that yields current mount state.useIsomorphicLayoutEffect
â LikeuseLayoutEffect
but falls back touseEffect
during 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
â LikeuseState
but its state setter is debounced.useFunctionalState
â LikeuseState
but 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 betrue
orfalse
.useThrottledState
â LikeuseState
but 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
â LikeuseMemo
but uses provided comparator function to validate dependency changes.useDeepCompareMemo
â LikeuseMemo
but uses@react-hookz/deep-equal
comparator function to validate deep dependency changes.useHookableRef
â LikeuseRef
but 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 providesAbortSignal
as 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
â UsesResizeObserver
to 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 wheneverResizeObserver
detects a change to the target's size.useScreenOrientation
â Checks if the screen is inportrait
orlandscape
orientation 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