GithubHelp home page GithubHelp logo

antonioru / beautiful-react-hooks Goto Github PK

View Code? Open in Web Editor NEW
8.0K 8.0K 565.0 6.09 MB

🔥 A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥

Home Page: https://antonioru.github.io/beautiful-react-hooks/

License: MIT License

JavaScript 51.13% TypeScript 48.79% Shell 0.07%
custom-hooks front-end hooks react react-components react-hooks

beautiful-react-hooks's People

Contributors

andreisena avatar antonioru avatar ayarushin avatar czeslaaw avatar danpoq avatar deevus avatar dependabot[bot] avatar dipiash avatar elanmedoff avatar ensarsnr avatar exkazuu avatar hsxfjames avatar koji avatar laviniu-creatopy avatar lindsay89 avatar linonetwo avatar little-buddy avatar mjschurig avatar pavlokozlov avatar phikes avatar playerony avatar rjmacarthy avatar semantic-release-bot avatar stevenselcuk avatar tal952 avatar wenzi0github avatar west0ne avatar yachelee avatar yoshino avatar yunghog avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

beautiful-react-hooks's Issues

[typescript] useResizeObserver does not support `null` or `undefined` type

Describe the bug
I have been using this project from time to time in our company codebase, but recently I tumble across this typescript issue with resize observer, is it intentional to typed it this way?

Screenshots
here is the type definition
image

but when I try to use it with initial value of null or undefined it gives type error since does not support those types
image

also, the docs from this repo show this that's why I'm confused. Thanks
image

useDebouncedFn seems not debounce

Describe the bug

I'm calling useDebouncedFn in onChange

  const setOutsideValue = useDebouncedFn(() => {
    console.log('called');
    
  }, 500)


  return (
    <Slate editor={editor} value={value} onChange={nextValue => {setValue(nextValue);setOutsideValue()}}>

And it is called as much as I type, after 500ms.

Screen Shot 2020-02-20 at 8 25 20 PM

To Reproduce
Add later...

(Update: https://stackblitz.com/edit/react-ombwbo)

Expected behavior
Only called 500ms a time.

Desktop (please complete the following information):

  • Electron 8.0.1

useResizeObserver causes "Can't perform a React state update on an unmounted component." error

Describe the bug
useResizeObserver can trigger the "Can't perform a React state update on an unmounted component." error.

To Reproduce
Minimal setup:

import { useInterval, useResizeObserver } from 'beautiful-react-hooks';
import React from 'react';

const Test = () => {
	const ref = React.useRef();
	useResizeObserver(ref, 510);

	return <div ref={ref}>TEST</div>;
};

export const App = () => {
	const [show, setShow] = React.useState(false);

	useInterval(() => {
		setShow((lastState) => !lastState);
	}, 500);

	return <div>{show && <Test />}</div>;
};

Expected behavior
No error is thrown. 

Desktop (please complete the following information):

  • OS: macOS 11.2.2
  • Browser Chrome 88.0.4324.192

Additional context
This error is caused by debounced callback trying to call setDOMRect on unmounted component. It can be fixed by either checking if the element is attached to DOM or by canceling debounced callback. I couldn't make it work by canceling debounced callback though. If I have some time I will try to make a pull request.

PR: #230

Types are incorrect for useLocalStorage

Describe the bug
The setter for useLocalStorage has incorrect typing. Instead of itself being a function which takes in a parameter of generic type T, it is a function which takes in a function with a parameter of type T.

I believe this bug was introduced here:
9a38045
(as was mentioned in and released in 0.33.4 https://github.com/beautifulinteractions/beautiful-react-hooks/blob/14070e2c41709dbd974493895928c39d60b4c337/CHANGELOG.md#0334---2021-05-09)

To Reproduce
Steps to reproduce the behavior:

  1. Use Typescript

  2. Use the local storage hoook:

    const [notificationCount, setNotificationCount] = useLocalStorage<number>('foo', 0);
  3. Attempt to invoke the setter:

    setNotificationCount(1);
  4. Notice the error:

    Argument of type 'number' is not assignable to parameter of type '(arg: number) => unknown'.
    

Expected behavior
The setter works as expected, allowing it to take in an argument of the generic type, rather than it expecting a function which takes in that type.

window is not defined when using browser APIs during SSR

Describe the bug

When building my app server side, hooks that use browser APIs (useGeolocationEvents, useMediaQuery, useOnlineState) cause the build to fail because they do not check if window is defined before checking for support.

Expected behavior
Hooks that utilize browser APIs should check if window is available. For example:

const isSupported = typeof window !== 'undefined' && 'geolocation' in window.navigator;

TypeScript: This expression is not callable. Type 'Cancelable' has no call signatures.

The TypeScript definition is incorrect for useDebouncedFn

https://github.com/beautifulinteractions/beautiful-react-hooks/blob/13d661285700b96fddfad3f29bec6f1e97943c63/index.d.ts#L28

The hook return a Function but the type is Cancelable which is not callable and so the following error is thrown:

This expression is not callable. Type 'Cancelable' has no call signatures.

Suggest that a new type could be the following:

 export declare const useDebouncedFn: <F extends Function>(fn: F, wait?: number, options?: ThrottleOrDebounceOpts, dependencies?: DependencyList) => F & Cancelable; 

useStorage: window is not defined

Describe the bug
Since beautiful-react-hooks v0.26.0, NextJS throws this error while building:

error - ReferenceError: window is not defined
    at Object.useStorage [as default] .../node_modules/beautiful-react-hooks/dist/useStorage.js:15:17)
    at Object.<anonymous> (.../node_modules/beautiful-react-hooks/dist/useLocalStorage.js:8:41)

The build fails.

To Reproduce
Steps to reproduce the behavior:

  1. Install [email protected] (or 0.26.)0
  2. Build using [email protected]

Expected behavior
Expect to build without errors.

useRequestAnimationFrame hook gives "Object(...) is not a function error" on SSR

Tried to use useRequestAnimationFrame on a project and when trying to use it, I end up with Object(...) is not a function error

To Reproduce
Steps to reproduce the behavior:

  1. Import import { useRequestAnimationFrame } from 'beautiful-react-hooks';
  2. Add the hook in the component
import { useRequestAnimationFrame } from 'beautiful-react-hooks';

const MyComponent = ({ someProp, ...props }) => {
    const options = { finishAt: -1 };

    useRequestAnimationFrame((progress, next) => {
       console.log('test');
    }, options);

    return (
        <div />
    );
};
  1. Go to webpage
  2. See error

Expected behavior
Obviously, have an RAF loop

Desktop (please complete the following information):

  • OS: High sierra 10.13.6
  • Browser: Chrome 79.0.3945.130

Additional context
Project is using Next.js

Missing types for useConditionalTimeout

types are accidentally missing on useConditionalTimeout

Expected Behavior

Types should be exported from the NPM package

Current Behavior

Types are not exported

useConditionalTimeout removed?

In #239 the useConditionalTimeout hook seems to also have been removed. Curious if this was due to an issue with the hook? I am relying on the hook for one of my projects.

100% code coverage

The current code coverage is around 84%, it would be nice to have a 100% score and I'd love to have some help in doing so. Please feel free to open any PR.

FYI: screenwidth example is broken in Firefox

Describe the bug
FYI: screenwidth example is broken in Firefox

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://beautifulinteractions.github.io/beautiful-react-hooks/#/useGlobalEvent
  2. Current window width: 1920 (even though I'm running 4k.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Win10, 4k monitor
  • Browser Firefox

Works fine in Chromium.
More of a FYI; Firefox only has 5% of the market.

MediaQueryList. addEventListener not working in Safari <= 13.1

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
use useMediaQuery in any component

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
image

Desktop (please complete the following information):

  • OS: iOS
  • Browser safari
  • Version <=13.1

Smartphone (please complete the following information):

  • Device: iPhone11
  • OS: iOS<14
  • Browser safari
  • Version <=13.1

Import Type definition for your custom Node ?

hey guys how i import the type for your node in custom render?
I test all what i know but am not able to find a ways !
image
Diagram seem not export Node type !
image

Actually the only hack i found and make success to get Intelisence types, is by add a default parameter

const CustomNode = (props = createSchema({}).nodes[0]) => {
	const { inputs } = props;

but am not fan with this ugly way !! , am search a way to add type in documentation
image

Any suggest ?, this React plugin look crazy contrat!
I'm just not a fan to code blinded. :)

maybe allow something like this for avoid <Any>?

/** custom renderer for Diagram Node
 * @param {Diagram['Node']} props - Current Node
*/
const CustomNode = (props) => { ...

Use dark mode

Is your feature request related to a problem? Please describe.
Missing a hook that allows easy dark mode usage.

I have been using https://github.com/donavon/use-dark-mode but it seems to me unsupported. It would be great if you could add a hook here.

Describe the solution you'd like
It should allow to toggle darkmode.
It should also allow to enable a feature that automatically reads out the prefer-color-scheme media query.

Invalid `HandlerSetter` type for `useGlobalEvent` hook

Describe the bug
The following PR introduced some breaking change in typings: https://github.com/beautifulinteractions/beautiful-react-hooks/pull/156/files#diff-b52768974e6bc0faccb7d4b75b162c99R19

Argument of type '() => void' is not assignable to parameter of type 'any[]'.
  Type '() => void' is missing the following properties from type 'any[]': pop, push, concat, join, and 27 more.  TS2345

     7 | 	const onWindowResize = useGlobalEvent('resize');
     8 | 
  >  9 | 	onWindowResize(() => {
       | 	               ^
    10 | 		setWindowWidth(window.innerWidth);
    11 | 	});
    12 |

I've tried the following, but of course, it is not working properly. But satisfies the TS compiler 😸

onWindowResize([
	() => {
		setWindowWidth(window.innerWidth);
	},
]);

Possible workaround

Use the third param of useGlovalEvent hook:

useGlobalEvent('resize', undefined, () => {
	setWindowWidth(window.innerWidth);
});

To Reproduce
I've prepared CRA repo to show this bug.
One with latest version --> compare: failling-issue-v0.30.5
And one with version that introduced the problematic change: compare: failling-issue-v0.30.1

Expected behavior
Well, I should have no TS compiler errors following hook examples. I know, these are JS examples, but we should either provide working TS versions of examples, or fix the typings. I vote for the latter one.

Screenshots
N/A

Desktop (please complete the following information):
N/A

Smartphone (please complete the following information):
N/A

Additional context

$ node --version && npm --version && yarn --version
v12.11.1
6.11.3
1.22.5

Running useViewportSpy on server side

Describe the bug
TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

To Reproduce
Steps to reproduce the behavior:

  1. Use Next.js to reproduce React app
  2. Setup this package and set ref to the `useViewportSpy
  3. See error

Expected behavior
No error produce

Screenshots
Screenshot 2020-06-17 at 3 04 04 PM

Desktop (please complete the following information):

  • OS: MacOS
  • Browser: Chrome, Firefox

Additional context
Use Nextjs for server side rendering

Incorrect MutableRefObject typings with --strictNullChecks option enabled

Hi! Thx for the awesome library. I've recently faced an issue with TS typings and prepared a fix (#232)
Here is the issue

Consider this code from the docs that is written in typescript

import { useRef } from 'react';
import { useViewportSpy } from 'beautiful-react-hooks';

const ViewportSpyComponent = () => {
    const ref = useRef<HtmlElement>();
    const isVisible = useViewportSpy(ref);

    return (
        <div>
            <div ref={ref} style={{padding: '20px 0', background: '#1D6C8B'}}>
                Observed element
            </div>
            <div style={{margin: '20px 0'}}>
                is the observed element in viewport? {isVisible ? 'yes': 'no'}
            </div>
        </div>
    );
};

with --strictNullChecks option enabled it gives me the following errors:

  1. TS2345: Argument of type 'MutableRefObject<HTMLElement | undefined>' is not assignable to parameter of type 'MutableRefObject'.   Type 'HTMLElement | undefined' is not assignable to type 'HTMLElement'.     Type 'undefined' is not assignable to type 'HTMLElement'.
  2. TS2322: Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type 'LegacyRef | undefined'.   Type 'MutableRefObject<HTMLElement | undefined>' is not assignable to type 'RefObject'.     Types of property 'current' are incompatible.       Type 'HTMLElement | undefined' is not assignable to type 'HTMLDivElement | null'.         Type 'undefined' is not assignable to type 'HTMLDivElement | null'.

This issue is valid for all hooks that use MutableRefObject as argument

What can we do to fix this?

  1. Change typings from
export declare const useViewportSpy: (elementRef: MutableRefObject<HTMLElement>, options?: IntersectionObserverInit) => boolean;

to

export declare const useViewportSpy: (elementRef: MutableRefObject<HTMLElement | null | undefined>, options?: IntersectionObserverInit) => boolean;
  1. change the docs to favor useRef(null) over userRef()

Thx!

useViewPort hook after contents seen

When the contents doesn't appear in the corresponding viewport anymore or once the contents have been seen by the user, the hook need to disconnect, otherwise, it will perform redundant rendering via state update on intersectionObserver. There should be an option to allow whether to allow this behavior or not flexibly.

Translation of doc

Is your feature request related to a problem? Please describe.
I would like to contribute a translation of documentation to Chinese.

Describe the solution you'd like
I think if react-styleguidist have a solution for i18n it would be great, but I've searched for a solution still no found a proper way to do so.

Describe alternatives you've considered
Maybe I can set up GitHub pages in my forked repo to serve translated files, and you can add a link to that github page?

Or maybe use react-i18n? styleguidist/react-styleguidist#335

Additional context

I asked in their Gitter channel, getting no response https://gitter.im/styleguidist/styleguidist?at=5e56138d1c4f1707f8cee035

proposing: useConditionalTimeout

This hook could be useful to delays the execution of the given function by the defined time when the condition is verified.

It accepts a callback function, a delay time in milliseconds and a condition.

`useSessionStorage`

Describe the solution you'd like
I'd like to have an hook to manage sessionStorage

It can be done easily by copy-pasting useLocalStorage code and changing the window method from window.localStorage.* to window.sessionStorage.*.

Alternatives
An hook to manage both the storage types, something like the following:

	const [count,setCount] = useStorage('local', 0)

useLocalStorage does not sync between multiple instances

Describe the bug

Two instances of the useLocalStorage are not synced between each other

To Reproduce

Check the following js fiddle that boils down the problem as much as possible: https://codesandbox.io/s/react-boilerplate-forked-s4hz2

Expected behavior

All instances of the hook force a rerender when the underlying value changes

Desktop (please complete the following information):

  • OS: Ubuntu 21.04
  • Browser chrome
  • Version 94.0.4606.71

Suggestion

This can be easily implemented by adding a listener to Window storage event

Tests are not running

Describe the bug
When I try to run the tests it uses 100% of CPU and crashes the machine.

To Reproduce
Steps to reproduce the behavior:

  1. Clone the project
  2. Run npm install
  3. Run npm run build
  4. Run npm run test

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
https://imgur.com/a/OInPuYq
https://imgur.com/a/uFuHOKo

Desktop (please complete the following information):

  • OS: 2 Ubuntu (20.04 and 18.04) / 1 Windows 10

Additional context
I alaso tried to change few versions of the libraries used but every time it hits, for example, the renderHooks function it freezes.

useMediaQuery in Next.js produces "Warning: Expected server HTML to contain a matching <div> in <div>."

Describe the bug
If you use in a Next.js Application useMedaQuery it results in the same issue described here:
vercel/next.js#17443

To Reproduce
Steps to reproduce the behavior:

  1. Use Next.js Application and implement useMedaQuery in one Component
  2. Load the dev environment of that Application
  3. Open Browser Console ( any current Firefox or CHrome will do)
  4. Press F5 in Browser to reload
  5. See error in console

Expected behavior
No error is thrown, as it further breaks reloading CSS in Next.js Dev Application and probably more.

Additional context
Following this amazing description: https://dev.to/adrien/creating-a-custom-react-hook-to-get-the-window-s-dimensions-in-next-js-135k it works for me like this right now:

import { useEffect, useState } from 'react';

const useMediaQuery = (mediaQuery: string): boolean => {
  const [isVerified, setIsVerified] = useState(false);

  useEffect(() => {
    const mediaQueryList = window.matchMedia(mediaQuery);
    const documentChangeHandler = (): void => setIsVerified(!!mediaQueryList.matches);

    try {
      mediaQueryList.addEventListener('change', documentChangeHandler);
    } catch (e) {
      // Safari isn't supporting mediaQueryList.addEventListener
      mediaQueryList.addListener(documentChangeHandler);
    }

    documentChangeHandler();

    return (): void => {
      try {
        mediaQueryList.removeEventListener('change', documentChangeHandler);
      } catch (e) {
        // Safari isn't supporting mediaQueryList.removeEventListener
        mediaQueryList.removeListener(documentChangeHandler);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Empty array ensures that effect is only run on mount

  return isVerified;
};

export { useMediaQuery };

useDebouncedFn docs and comment fix

Comment in file useDebouncedFn.js

/**
 * Accepts a function and returns a new debounced yet memoized version of that same function that delays
 * its invoking by the defined time.
 * If time is not defined, its default value will be 250ms.
 */
const useDebouncedFn = (fn, wait = 100, options = defaultOptions, dependencies) => {
  const debounced = debounce(fn, wait, options);

  return useCallback(debounced, dependencies);
};

export default useDebouncedFn;

I guess the right version of the comment have to be like that, because default wait value set to 100.

/**
 * Accepts a function and returns a new debounced yet memoized version of that same function that delays
 * its invoking by the defined time.
 * If time is not defined, its default value will be 100ms.
*/

Also in file useDebouncedFn.md inside "Options" paragraph

Since useDebouncedFn uses lodash.throttle under the hood, you can possibly define few options to customize its behaviour.

According to useDebouncedFn.js file useDebouncedFn hook is using lodash.debounce under the hood, so options paragraph could look like that

Since useDebouncedFn uses lodash.debounce under the hood, you can possibly define few options to customize its behaviour.

Treeshaking not supported?

I am just using the useViewportSpy hook and it seems like that all hooks, even if there not used, are landing in the bundle file?!

Traditional class-based state in hooks

Is your feature request related to a problem? Please describe.
I often come across problems where I want to use the traditional approach to state / setState as in class components.

Describe the solution you'd like
I propose to implement useComplexState, which return [state, setState].

You can pass objects only.

Example:

const [state, setState] = useComplexState({ 
     foo: 1,
     bar: 2
})

setState({
     foo: 3
})

console.log(state);

// {
//     foo: 3,
//     bar: 2
// }

Ready to contribute by myself 😋

isDevelopment in webpack v5 causes an error 'process is not defined'

Describe the bug
webpack v5 doesn't provide a mock of process, so isDevelopment causes an error 'process is not defined'.
(Note that webpack.DefinePlugin replace just process.env.NODE_ENV (not process), so process is still undefined even if process.env.NODE_ENV is available.)

To Reproduce

  1. Build a web app depending beautiful-react-hooks with webpack v5
  2. Open the web app
  3. Uncaught ReferenceError: process is not defined is shown in console

Expected behavior
No error is shown.

Desktop:

  • OS: any (I use Mac OS)
  • Browser: any (I use Chrome 85)
  • Version: beautiful-react-hooks v0.30.5

Hooks dependencies check needed

Some useEffect and useCallback may be currently running with a wrong list of dependencies, this may lead to some bug/unexpected behaviour. A dependencies check is needed.

Switch codebase to typescript

Is your feature request related to a problem? Please describe.
Switching to typescript or adding type hints can increase the usability in the long run.

Describe the solution you'd like
Convert all the files one by one

Unable to preventDefault inside passive event listener due to target being treated as passive.

Describe the bug
When using useSwipe or useSwipeEvents, the console of Chrome DevTools shows error logs like below.

bundle.9dceb1d3.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080

I confirmed that passing the passvie: false options to addEventListener solves this plobrem.

target.addEventListener(eventName, cb, { passive: false })

↑ code is here

To Reproduce
Steps to reproduce the behavior:

  1. Go to useSwipe Live demo
  2. Fire swipe events in global example or options example
  3. Open Chrome DevTools
  4. See error

Expected behavior
These hooks can set preventDefault value as option and , the console of Chrome DevTools shows no error.

Desktop (please complete the following information):

  • OS: Ubuntu
  • Browser: chrome
  • Version: 91.0.4472.77

Object is not a function or its return value is not iterable with in SSR apps

Describe the bug
useLocalStorage hook is not working in SSR projects.

To Reproduce
Steps to reproduce the behavior:

  1. I have created Next.js app
  2. I added this library into my project
  3. I use useLocalStorage hook in page component (FC)
    const MainLayout: FC<MainLayoutProps> = ({ children, mode, menuAbsolute, userId }) => {
       const [items] = useLocalStorage('items', [])
       
       return (<>{items?.length || 0}</>)
    }
  4. After that page was built, during the render I see the error
    Object is not a function or its return value is not iterable with in SSR apps

Expected behavior
I expected to happen that I get default value on server side. I don't want to wrap this code into dynamic component.

Screenshots
Снимок экрана 2020-05-07 в 23 06 28

Support ES Modules

Is your feature request related to a problem? Please describe.
I'm trying to export my React app as a component and I'm using beautiful-react-hooks.
Currently this library is only exported as CommonJS module, so it is not tree-shakable.

Describe the solution you'd like
Add a ESModule file in rollup.config.js. It is format: es in output.

useInterval doesn't reset previous interval when milliseconds changes

https://github.com/beautifulinteractions/beautiful-react-hooks/blob/2f3475998347e5bb6220e7371d611649a09930a9/src/useInterval.js#L32

According to comments in code, it should reset timeout, but here is only code for producing new interval.

    // when the milliseconds change, reset the timeout
    useEffect(() => {
        // clear previous interval
        clear();

        if (typeof milliseconds === 'number') {
            timeout.current = setInterval(() => {
                callback.current();
            }, milliseconds);
        }
    }, [milliseconds]);

useGlobalEvent does not update when handler function changes

Describe the bug
As of this change in May 58907dc#diff-0a8432ca913ab2abf25a4371c9b5336ce6d6aad4c102d01aa3c862d747dd79c7L16-L17, useGlobalEvent broke, since changes to the handler function do not update the local ref (and so stale versions of the handler will be called). It seems likely that this will have affected other hooks as well.

To Reproduce
Steps to reproduce the behavior:

  1. Use useGlobalEvent with a callback that changes, e.g.:
    const [num, setNum] = useState(0);
    useGlobalEvent("keydown", undefined, () => {
      console.log("keydown num is ", num);
      setNum((prevNum) => prevNum + 1);
    });
    console.log("actual num is ", num);
  2. Press any key
  3. Notice in the console that actual num is ... keeps incrementing, while the former log statement will always read keydown num is 0, despite the fact that the handler for useGlobalEvent is an arrow-function that is redefined on every render. (The first version of the callback is stored and so useGlobalEvent is stale)

Example from the above demo:

21:14:21.821 Main.tsx:31 actual num is  0
21:14:21.923 Main.tsx:31 actual num is  0
21:14:25.936 Main.tsx:28 keydown num is  0
21:14:25.936 Main.tsx:31 actual num is  1
21:14:26.670 Main.tsx:28 keydown num is  0
21:14:26.671 Main.tsx:31 actual num is  2
21:14:27.887 Main.tsx:28 keydown num is  0
21:14:27.888 Main.tsx:31 actual num is  3

Additional context
It seems this line should have handlerValue as the useCallback dependency, rather than handlerRef, which will never cause the callback to update: 58907dc#diff-0a8432ca913ab2abf25a4371c9b5336ce6d6aad4c102d01aa3c862d747dd79c7R22

set up Travis CI for this repository

Setup Travis CI for this repository:

  • Clear the local modules
  • Install everything again
  • running the tests
  • build the library
  • If the destination branch is master, pubish the content of the dist-ghpages directory to the branch ghpages
  • if the destination branch is master, publish the new version of the library to npm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.