@react-hookz/web is a library of general-purpose React hooks built with care and SSR compatibility in mind.

Overview

@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 does not do so either. You'll have to transpile your node-modules in order to run in IE.

Usage

This package provides three levels of compilation:

  1. Main, the /cjs folder — CommonJS modules, with ES5 lang level.
  2. ESM, the /esm folder — it is ES modules (browser compatible), with ES5 lang level.
  3. ESNext, the /esnext folder — it is ES modules (browser compatible), with ESNext lang level.

So, if you need the useMountEffect hook, depending on your needs, you can import in three ways (there are actually more, but these are the three most common):

// in case you need cjs modules
import { useMountEffect } from "@react-hookz/web";
// in case you need esm modules
import { useMountEffect } from "@react-hookz/web/esm";
// in case you want all the recent ES features
import { useMountEffect } from "@react-hookz/web/esnext";

Hooks list

  • Callback

    • useDebounceCallback — Makes passed function debounced, otherwise acts like useCallback.
    • useRafCallback — Makes passed function to be called within next animation frame.
  • Lifecycle

  • State

    • useMediatedState — Like useState, but every value set is passed through a mediator function.
    • usePrevious — Returns the value passed to the hook on previous render.
    • useSafeState — Like useState, but its state setter is guarded against sets on unmounted component.
    • useToggle — Like useState, but can only become true or false.
  • Navigator

  • Miscellaneous

    • useSyncedRef — Like useRef, but it returns immutable ref that contains actual value.
  • Side-effect

  • Sensor

    • useResizeObserver — Invokes a callback whenever ResizeObserver detects a change to target's size.
    • useMeasure — Uses ResizeObserver to track element dimensions and re-render component when they change.
  • Dom

Issues
  • feat: new hooks, useConditionalEffect and useConditionalUpdateEffect

    feat: new hooks, useConditionalEffect and useConditionalUpdateEffect

    What new hook does?

    • useConditionalEffect - Alike useEffect but callback invoked only if conditions match predicate.
    • useConditionalUpdateEffect — Alike useUpdateEffect but callback invoked only if conditions match predicate.

    Checklist

    • [x] Have you read contribution guideline?
    • [x] Does the code have comments in hard-to-understand areas?
    • [ ] Is there an existing issue for this PR?
      • link issue here
    • [x] Have the files been linted and formatted?
    • [x] Have the docs been updated?
    • [x] Have the tests been added to cover new hook?
    • [x] Have you run the tests locally to confirm they pass?
    new hook released 
    opened by xobotyi 12
  • feat: new hook useIsMounted

    feat: new hook useIsMounted

    What new hook does?

    Returns function that yields current mount state.

    Checklist

    • [x] Have you read contribution guideline?
    • [x] Does the code have comments in hard-to-understand areas?
    • [ ] Is there an existing issue for this PR?
      • link issue here
    • [x] Have the files been linted and formatted?
    • [x] Have the docs been updated?
    • [x] Have the tests been added to cover new hook?
    • [x] Have you run the tests locally to confirm they pass?
    new hook released 
    opened by xobotyi 10
  • feat: new hook `useTitle`

    feat: new hook `useTitle`

    What new hook does?

    Sets title of the page.

    Checklist

    • [x] Have you read contribution guideline?
    • [x] Does the code have comments in hard-to-understand areas?
    • [x] Is there an existing issue for this PR?
      • #33
    • [x] Have the files been linted and formatted?
    • [x] Have the docs been updated?
    • [x] Have the tests been added to cover new hook?
    • [x] Have you run the tests locally to confirm they pass?
    new hook released 
    opened by xobotyi 9
  • fix the examples of useAsync

    fix the examples of useAsync

    What is the problem?

    useAsync gives wrong examples

    What changes does this PR make to fix the problem?

    correct the example

    Checklist

    • [x] Is there an existing issue for this PR?
      • fix: #343
    released 
    opened by Rey-Wang 8
  • feat: add `initializeWithValue` option to `useCookie` hook

    feat: add `initializeWithValue` option to `useCookie` hook

    BREAKING CHANGE: useCookie renamed to useCookieValue

    BREAKING CHANGE: useCookieValue default behaviour for browsers changed to fetch cookie value on state initialisation.

    SSR remains untouched, but requires implicit setting of initializeWithValue option to false, to avoid hydration mismatch.

    What is the current behavior, and the steps to reproduce the issue?

    Hook fetches cookie value onli on effects execution stage, thus first render always yields undefined state.

    What is the expected behavior?

    Ability to enable or disable initialisation fetch.

    How does this PR fix the problem?

    Add initializeWithValue option to disable initialisation value fetch and make hook to fetch value on initialisation by default.

    Checklist

    • [x] Have you read contribution guideline?
    • [x] Have you added an explanation of what your changes do and why you'd like us to include them?
    • [ ] Is there an existing issue for this PR?
      • link issue here
    • [x] Have the files been linted and formatted?
    • [x] Have the docs been updated to match the changes in the PR?
    • [x] Have the tests been updated to match the changes in the PR?
    • [x] Have you run the tests locally to confirm they pass?
    enhancement released 
    opened by xobotyi 7
  • feat: new hooks `useLocalStorageValue` and `useSessionStorageValue`

    feat: new hooks `useLocalStorageValue` and `useSessionStorageValue`

    What new hook does?

    Add new hooks to manage localStorage and sessionStorage keys

    Checklist

    • [x] Have you read contribution guideline?
    • [x] Does the code have comments in hard-to-understand areas?
    • [x] Is there an existing issue for this PR?
      • #33
    • [x] Have the files been linted and formatted?
    • [x] Have the docs been updated?
    • [x] Have the tests been added to cover new hook?
    • [x] Have you run the tests locally to confirm they pass?
    new hook released 
    opened by xobotyi 7
  • `useMountEffect` can't return a clean-up function

    `useMountEffect` can't return a clean-up function

    What is the current behavior?

    export function useMountEffect(effect: CallableFunction): void {
      useEffect(() => {
        effect();
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, []);
    }
    
    

    Steps to Reproduce

    When the effect returns a clean-up function, the function can't be working.

    What is the expected behavior?

    Sometimes, we hope to subscribe to something(like WebSocket?) when the component be mounted. And we must unsubscribe it when the component is unmounted. Currently useMountEffect does not support returning a clean-up function.

    Perhaps it needs to be changed to

    export function useMountEffect(effect: CallableFunction): void {
      useEffect(
        () => effect(),
        // eslint-disable-next-line react-hooks/exhaustive-deps
        []
      );
    }
    
    question wontfix 
    opened by nuanyang233 6
  • feat: new hook `useSyncedRef`

    feat: new hook `useSyncedRef`

    What new hook does?

    Like useRef, but it returns immutable ref that contains actual value.

    I'm not sure about hook naming, i dont really like the useSyncedRef, but it is the best i came up with.

    Checklist

    • [x] Have you read contribution guideline?
    • [x] Does the code have comments in hard-to-understand areas?
    • [ ] Is there an existing issue for this PR?
      • link issue here
    • [x] Have the files been linted and formatted?
    • [x] Have the docs been updated?
    • [x] Have the tests been added to cover new hook?
    • [x] Have you run the tests locally to confirm they pass?
    new hook released 
    opened by xobotyi 6
  • docs: docs for some docless components

    docs: docs for some docless components

    What is the problem?

    Docs were missing for some components

    What changes does this PR make to fix the problem?

    • [x] Docs for useMountEffect
    • [x] Docs for useRerender
    • [x] Docs for useToggle
    • [x] Docs for useUnmountEffect

    Checklist

    • [ ] Is there an existing issue for this PR?
      • link issue here
    released 
    opened by JoeDuncko 6
  • Remove `types` field in package.json

    Remove `types` field in package.json

    The types folder is not published. I think this should do it.

    opened by axelboc 6
  • feat(useFavicon): port `useFavicon` from `react-use`

    feat(useFavicon): port `useFavicon` from `react-use`

    What new hook does?

    Checklist

    • [x] Have you read contribution guideline?
    • [ ] Does the code have comments in hard-to-understand areas?
    • [ ] Is there an existing issue for this PR?
      • #33
    • [x] Have the files been linted and formatted?
    • [x] Have the docs been updated?
    • [x] Have the tests been added to cover new hook?
    • [x] Have you run the tests locally to confirm they pass?
    opened by alexnaiman 2
  • fix(src/index.ts): Add missing export for useCookieValue and fix typo…

    fix(src/index.ts): Add missing export for useCookieValue and fix typo…

    Fix a typo and add useCookieValue export to top index.ts file.

    opened by thornyweb 1
  • `useConditionalEffect` dependencies conflicts with predicates

    `useConditionalEffect` dependencies conflicts with predicates

    What is the current behavior?

    Using an empty deps array forces the effect to run only once while disregarding the predicates. The same applies if there are deps in the array, but the predicates aren't truthy at the time it runs.

    The issue surfaces mostly when using refs as predicates, since those can't be used as deps for the effect.

    useConditionalEffect(
      () => {},
      [],
      [!!ref.current]
    )
    

    What is the expected behavior?

    [] should equal undefined (but run only once), so respecting the predicates.

    Possible solution

    Set the deps to undefined internally until the effect can run once following the predicates, then stopping further runs.

    Environment Details

    • @react-hookz/web version: 11.0.0
    • react version: 17.0.2
    • react-dom version: 17.0.2
    • OS: Big Sur
    • Browser: All
    • Did this work in previous versions? I don't think so
    bug 
    opened by fcisio 2
  • Create an example for `useCustomCompareEffect`

    Create an example for `useCustomCompareEffect`

    What docs page needs to be fixed?

    • Section:
    • Page:

    What is the problem?

    Currently useCustomCompareEffect does not have an example in the docs. We should make one.

    What should be changed to fix the problem?

    documentation 
    opened by JoeDuncko 4
  • [querySubscribe()]: mql_1.addEventListener is not a function

    [querySubscribe()]: mql_1.addEventListener is not a function

    What is the current behavior?

    useMediaQuery's querySubscribe() fails on iOS 12

    mql_1.addEventListener is not a function. (In 'mql_1.addEventListener('change', listener, { passive: true })', 'mql_1.addEventListener' is undefined)

    Steps to Reproduce

    On iOS 12

    1. Add a useMediaQuery
    2. Serve to the device

    What is the expected behavior?

    The project should run without bugs and warnings

    Environment Details

    • @react-hookz/web version: 7.0.0
    • react version: 17.0.2
    • react-dom version: 17.0.2
    • Browser: All IOS Browsers
    • Did this work in previous versions? No
    bug 
    opened by fcisio 8
  • Port remaining hooks from `react-use`

    Port remaining hooks from `react-use`

    Our goal with @react-hookz/web is to give the react community a general-purpose React hooks library built with care.

    We'd like to port the remaining hooks from react-use (the project @react-hookz/web grew out of) while keeping in mind our tenants:

    • General-purposeness (hooks should fulfill a wide array of use cases)
    • Composability (a preference for hooks that are useful for building other hooks)
    • No or very few dependencies
    • SSR compatibility
    • 100% test coverage (ideally)
    • Concrete example use cases

    Hooks to port

    Sensors

    UI

    • [ ] useAudio — plays audio and exposes its controls.
    • [x] useClickAway — triggers callback when user clicks outside target area. (Implmented as useClickOutside)
    • [ ] useCss — dynamically adjusts CSS.
    • [ ] useDrop — tracks file, link and copy-paste drops.
    • [ ] useDropArea — tracks file, link and copy-paste drops.
    • [ ] useFullscreen — display an element or video full-screen.
    • [ ] useSlider — provides slide behavior over any HTML element.
    • [ ] useSpeech — synthesizes speech from a text string.
    • [ ] useVibrate — provide physical feedback using the Vibration API.
    • [ ] useVideo — plays video, tracks its state, and exposes playback controls.

    Animations

    • [ ] useRaf — re-renders component on each requestAnimationFrame.
    • [ ] useInterval and useHarmonicIntervalFn — re-renders component on a set interval using setInterval.
    • [ ] useSpring — interpolates number over time according to spring dynamics.
    • [ ] useTimeout — re-renders component after a timeout.
    • [ ] useTimeoutFn — calls given function after a timeout.
    • [ ] useTween — re-renders component, while tweening a number from 0 to 1.
    • [x] useUpdate — returns a callback, which re-renders component when called. (Implemented as useRerender)

    Side-effects

    Lifecycles

    State

    Miscellaneous

    Join our community!

    Have a question? Create a discussion on GitHub or join our Discord community.

    Interested in contributing code? Check out our contribution guide. We are excited to see your pull request!

    enhancement help wanted good first issue new hook javascript 
    opened by JoeDuncko 14
Releases(v12.0.0)
Async HTTP request data for axios. Designed for diverse UI states, SSR and data pre-caching.

React useApi() Axios-based React hooks for async HTTP request data. react-use-api feeds API data to React components when SSR (Server-Side Rendering),

Ryan 58 Jul 19, 2021
😎 ♻️ A tiny React hook for rendering large datasets like a breeze.

?? ♻️ A tiny React hook for rendering large datasets like a breeze.

Welly 829 Oct 8, 2021
React Native APIs turned into React Hooks for use in functional React components

React Native Hooks React Native APIs turned into React Hooks allowing you to access asynchronous APIs directly in your functional components. Note: Yo

React Native Community 2.6k Oct 17, 2021
Essential React custom hooks ⚓ to super charge your components!

Essential React custom hooks ⚓ to super charge your components!

Bhargav Ponnapalli 1.9k Oct 16, 2021
Learn Advanced React Hooks workshop

Learn the more advanced React hooks and different patterns to enable great developer APIs for custom hooks.

Kent C. Dodds 1.4k Oct 21, 2021
Learn React Hooks! 🎣 ⚛

Learn the ins and outs of React Hooks. I will take you on a deep dive into React Hooks, and show you what you need to know to start using them in your applications right away.

Kent C. Dodds 1.9k Oct 19, 2021
☯️ React hook to determine if you are on the server, browser, or react native

useSSR ☯️ React hook to determine if you are on the server, browser, or react native Need to know when you're on the server, in the browser or in reac

Alex Cory 241 Sep 22, 2021
Understand how React-hook really behaves, once and for all!

Understand how React-hook really behaves, once and for all!

null 63 Oct 4, 2021
React custom hooks for async functions with abortability and composability

react-hooks-async React custom hooks for async functions with abortability and composability Introduction JavaScript promises are not abortable/cancel

Daishi Kato 493 Oct 14, 2021
Simple global state for React with Hooks API without Context API

react-hooks-global-state Simple global state for React with Hooks API without Context API Introduction This is a library to provide a global state wit

Daishi Kato 725 Oct 6, 2021
React Redux binding with React Hooks and Proxy

There are several projects related to this repo. Here's the index of those. reactive-react-redux v5-alpha (this repo): This has an experimental react-

Daishi Kato 502 Oct 6, 2021
😎 🍿 React hook for highly-performant and manipulable animations using Web Animations API.

USE-WEB-ANIMATIONS Using Web Animations API (a.k.a WAAPI) in the React hook way. Let's create highly-performant, flexible and manipulable web animatio

Welly 965 Oct 17, 2021
Redux-Toolkit example with React Hooks CRUD Application, Axios, Rest API, Bootstrap

Redux-Toolkit example with React Hooks CRUD Application, Axios, Rest API, Bootstrap

null 7 Oct 11, 2021
React Hooks — 👍

Collaborative editing for your app. Support on Kickstarter! ?? react-use Collection of essential React Hooks. Port of libreact. Translations: ???? 汉语

Vadim Dalecky 25.9k Oct 18, 2021
hooks-first CSS-in-JS library, focused on semantics and runtime performance

Trousers ?? React components are more stylish with Trousers! Try it here Trousers is a hooks-first CSS-in-JS library, designed to help developers auth

Daniel Del Core 296 Sep 8, 2021
Dependency injection for React hooks

React Facade An experimental library that uses Proxy and TypeScript to create a strongly typed facade for your React hooks. Dependency inversion betwe

Gabe Scholz 59 Oct 13, 2021
React Hooks for Firebase.

React Firebase Hooks A set of reusable React Hooks for Firebase. Official support for Hooks was added to React Native in v0.59.0. React Firebase Hooks

CS Frequency 2.1k Oct 13, 2021
Testing hooks with Jest

Jooks (Jest ❤ + Hooks ????) If you're going through hell testing React Hooks, keep going. (Churchill) What are Custom React Hooks React Hooks are a ne

Antoine Jaussoin 74 Oct 9, 2021
🐶 React hook for making isomorphic http requests

useFetch ?? React hook for making isomorphic http requests Main Documentation npm i use-http Features SSR (server side rendering) support TypeScript s

Ava 2k Oct 17, 2021