Convert Figma logo to code with AI

react-hookz logoweb

React hooks done right, for browser and SSR.

1,889
93
1,889
31

Top Related Projects

41,619

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

46,119

🐻 Bear necessities for state management in React

The official, opinionated, batteries-included toolset for efficient Redux development

41,619

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

19,568

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

  1. 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>
  );
}
  1. 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..."
    />
  );
}
  1. 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:

  1. Install the package:

    npm install @react-hookz/web
    
  2. 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);
      // ...
    }
    
  3. Refer to the official documentation for detailed usage instructions and available hooks.

Competitor Comparisons

41,619

🤖 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.

46,119

🐻 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.

41,619

🤖 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.

19,568

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 Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

@react-hookz/web

NPM Version NPM Downloads NPM Dependents Build Coverage Types Tree Shaking

× DOCS × DISCORD × CHANGELOG ×


@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 like useCallback.
    • useRafCallback — Makes passed function to be called within next animation frame.
    • useThrottledCallback — Makes passed function throttled, otherwise acts like useCallback.
  • Lifecycle

    • useConditionalEffect — Like useEffect but callback invoked only if given conditions match a given predicate.
    • useCustomCompareEffect — Like useEffect but uses a provided comparator function to validate dependency changes.
    • useDebouncedEffect — Like useEffect, but passed function is debounced.
    • useDeepCompareEffect — Like useEffect but uses @react-hookz/deep-equal comparator function to validate deep dependency changes.
    • useFirstMountState — Returns a boolean that is true only on first render.
    • useIntervalEffect — Like setInterval but in the form of a React hook.
    • useIsMounted — Returns a function that yields current mount state.
    • useIsomorphicLayoutEffect — Like useLayoutEffect but falls back to useEffect during SSR.
    • useMountEffect — Run an effect only when a component mounts.
    • useRafEffect — Like useEffect, but the effect is only run within an animation frame.
    • useRerender — Returns a callback that re-renders the component.
    • useThrottledEffect — Like useEffect, but the passed function is throttled.
    • useTimeoutEffect — Like setTimeout, 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 — Like useState, but its state setter accepts an extra argument, that allows cancelling renders.
    • useCounter — Tracks a numeric value and offers functions for manipulating it.
    • useDebouncedState — Like useState but its state setter is debounced.
    • useFunctionalState — Like useState 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 a Map.
    • useMediatedState — Like useState, 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 — Like React.useState, but state is only updated within animation frame.
    • useRenderCount — Tracks component's render count including first render.
    • useSet — Tracks the state of a Set.
    • useToggle — Like useState, but can only be true or false.
    • useThrottledState — Like useState 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 — Like useRef, but it returns an immutable ref that contains the actual value.
    • useCustomCompareMemo — Like useMemo but uses provided comparator function to validate dependency changes.
    • useDeepCompareMemo — Like useMemo but uses @react-hookz/deep-equal comparator function to validate deep dependency changes.
    • useHookableRef — Like useRef but it is possible to define handlers for getting and setting the value.
  • Side-effect

  • Sensor

    • useIntersectionObserver — Observe changes in the intersection of a target element with an ancestor element or with the viewport.
    • useMeasure — Uses ResizeObserver 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 whenever ResizeObserver detects a change to the target's size.
    • useScreenOrientation — Checks if the screen is in portrait or landscape 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

xobotyi
Anton Zinovyev
JoeDuncko
Joe Duncko
ArttuOll
Arttu Olli
kylemh
Kyle Holmberg
wesgro
Jake Ketcheson
Rey-Wang
Rey Wang
AndreasNel
Andreas Nel
fengkx
Fengkx
paul-sachs
Paul Sachs
Myzel394
Null
MichalTarasiuk
Michał Tarasiuk
KonradLinkowski
Konrad Linkowski
jpwallace22
Justin Wallace
JoshuaStewartEntelect
Joshua Stewart
dantman
Daniel Friesen
ChloeMouret
Null
punkle
Brian Fletcher
birant
Birant İyigün
lensbart
Bart Lens
axelboc
Axel Bocciarelli
akd-io
Anders Kjær Damgaard

NPM DownloadsLast 30 Days