web
web copied to clipboard
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
- [ ] useBattery — tracks device battery state.
- [ ] useGeolocation — tracks geo location state of user's device.
- [ ] useHover — tracks mouse hover state of some element.
- [ ] useHoverDirty — tracks mouse hover state of some element.
- [x] ~~useHash — tracks location hash value.~~ (No plans to implement. Instead, use one the various routing libraries available.)
- [ ] useIdle — tracks whether user is being inactive.
- [x] useIntersection — tracks an HTML element's intersection. (Implemented as useIntersectionObserver)
- [x] ~~useKey — track keys.~~ (Implemented as useKeyboardEvent)
- [x] ~~useKeyPress — track keys.~~ (Implemented as useKeyboardEvent)
- [x] ~~useKeyboardJs — track keys.~~ (Implemented as useKeyboardEvent)
- [x] ~~useKeyPressEvent — track keys.~~ (Implemented as useKeyboardEvent)
- [x] ~~useLocation — tracks page navigation bar location state.~~ (No plans to implement. Instead, use one the various routing libraries available.)
- [x] ~~useSearchParam — tracks page navigation bar location state.~~ (No plans to implement. Instead, use one the various routing libraries available.)
- [ ] useLongPress — tracks long press gesture of some element.
- [x] useMedia — tracks state of a CSS media query. (implemented as useMediaQuery)
- [ ] useMediaDevices — tracks state of connected hardware devices.
- [ ] useMotion — tracks state of device's motion sensor.
- [ ] useMouse — tracks state of mouse position.
- [ ] useMouseHovered — tracks state of mouse position.
- [ ] useMouseWheel — tracks deltaY of scrolled mouse wheel.
- [x] useNetworkState — tracks the state of browser's network connection. (implemented as useNetwork)
- [ ] useOrientation — tracks state of device's screen orientation.
- [ ] usePageLeave — triggers when mouse leaves page boundaries.
- [ ] useScratch — tracks mouse click-and-scrub state.
- [ ] useScroll — tracks an HTML element's scroll position.
- [ ] useScrolling — tracks whether HTML element is scrolling.
- [ ] useStartTyping — detects when user starts typing.
- [ ] useWindowScroll — tracks Window scroll position.
- [x] useWindowSize — tracks Window dimensions.
- [x] useMeasure — tracks an HTML element's dimensions. (implemented as useMeasure)
- [x] ~~useSize — tracks an HTML element's dimensions.~~ (Use
useWindowSizeinstead) - [x] ~~createBreakpoint — tracks innerWidth~~ (Not planning to implement)
- [ ] useScrollbarWidth — detects browser's native scrollbars width.
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.
- [x] ~~useInterval and useHarmonicIntervalFn — re-renders component on a set interval using setInterval.~~ (Implemented as
useIntervalEffect). - [ ] useSpring — interpolates number over time according to spring dynamics.
- [x] ~~useTimeout — re-renders component after a timeout.~~ (Can be composed from other hooks, see migration guide).
- [x] ~~useTimeoutFn — calls given function after a timeout.~~ (Implemented as
useTimeoutEffect). - [ ] 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
- [x] useAsync — resolves an async function. (implemented as useAsync)
- [x] useAsyncFn — resolves an async function. (implemented as useAsync)
- [x] useAsyncRetry — resolves an async function. (implemented as useAsync)
- [x] ~~useBeforeUnload — shows browser alert when user try to reload or close the page.~~ (No plans to implement, address migration guide for workaround)
- [x] useCookie — provides way to read, update and delete a cookie. (implemented as useCookieValue)
- [x] ~~useCopyToClipboard — copies text to clipboard.~~ (no plans to implement - use browser's API instead)
- [x] useDebounce — debounces a function. (Implemented as useDebounceCallback)
- [ ] useError — error dispatcher.
- [x] ~~useFavicon — sets favicon of the page.~~ (Hooks that modify the element will not be implemented).
- [x] useLocalStorage — manages a value in localStorage. (Implemented as useLocalStorageValue)
- [ ] useLockBodyScroll — lock scrolling of the body element.
- [ ] useRafLoop — calls given function inside the RAF loop.
- [x] useSessionStorage — manages a value in sessionStorage. (Implemented as useSessionStorageValue)
- [x] useThrottle — throttles a function.
- [x] ~~useThrottleFn — throttles a function.~~
- [x] ~~useTitle — sets title of the page.~~ (Hooks that modify the element will not be implemented).
- [x] usePermission — query permission status for browser APIs. (Implemented as usePermission)
Lifecycles
- [x] ~~useEffectOnce — a modified useEffect hook that only runs once.~~ (it's just an alias for
useMountEffect) - [x] useEvent — subscribe to events. (Implemented as useEventListener)
- [x] ~~useLifecycles — calls mount and unmount callbacks.~~ (no sense to port, has almost no benefit comparing to
useEffect) - [x] useMountedState — track if component is mounted. (Implemented as useIsMounted)
- [x] ~~useUnmountPromise — track if component is mounted.~~ (No plans to implement).
- [x] ~~usePromise — resolves promise only while component is mounted.~~ (No plans to implement)
- [x] ~~useLogger — logs in console as component goes through life-cycles.~~ (Implemented as useLifecycleLogger
- [x] useMount — calls mount callbacks. (Implemented as useMountEffect)
- [x] useUnmount — calls unmount callbacks. (Implemented as useUnmountEffect)
- [x] useUpdateEffect — run an effect only on updates. (Implemented as useUpdateEffect)
- [x] useIsomorphicLayoutEffect — useLayoutEffect that does not show warning when server-side rendering. (Implemented as useIsomorphicLayoutEffect)
- [x] useDeepCompareEffect — run an effect depending on deep comparison of its dependencies. (Implemented as useDeepCompareEffect)
- [ ] useShallowCompareEffect — run an effect depending on deep comparison of its dependencies
- [x] useCustomCompareEffect — run an effect depending on deep comparison of its dependencies. (Implemented as useCustomCompareEffect)
State
- [x] ~~createMemo — factory of memoized hooks.~~ (Not planning to implement)
- [x] ~~createReducer — factory of reducer hooks with custom middleware.~~ (Not planning to implement)
- [x] ~~createReducerContext — factory of hooks for a sharing state between components.~~ (Not planning to implement)
- [x] ~~createStateContext — factory of hooks for a sharing state between components.~~ (Not planning to implement)
- [x] ~~useDefault — returns the default value when state is null or undefined.~~ (No plans to implement. Use useMediatedState instead).
- [x] ~~useGetSet — returns state getter get() instead of raw state.~~ (No plans to implement)
- [x] ~~useGetSetState — as if useGetSet and useSetState had a baby.~~ (No plans to implement)
- [x] useLatest — returns the latest state or props (Implemented as useSynchedRef)
- [x] usePrevious — returns the previous state or props. (Implemented as usePrevious)
- [x] usePreviousDistinct — like usePrevious but with a predicate to determine if previous should update. (Implemented as usePreviousDistinct)
- [ ] useObservable — tracks latest value of an Observable.
- [ ] useRafState — creates setState method which only updates after requestAnimationFrame.
- [x] ~~useSetState — creates setState method which works like this.setState.~~ (No plans to implement)
- [ ] useStateList — circularly iterates over an array.
- [x] useToggle — tracks state of a boolean. (Implemented as useToggle)
- [x] useBoolean — tracks state of a boolean. (Implemented as useToggle)
- [x] useCounter — tracks state of a number.
- [x] ~~useNumber — tracks state of a number.~~ (Implemented as useCounter)
- [x] useList — tracks state of an array.
- [x] ~~useUpsert — tracks state of an array.~~ (Use
useListinstead.) - [x] useMap — tracks state of an object. (Implemented as useMap)
- [x] useSet — tracks state of a Set. (Implemented as useSet)
- [x] useQueue — implements simple queue. (Implemented as useQueue)
- [x] useStateValidator — tracks state of an object.
- [ ] useStateWithHistory — stores previous state values and provides handles to travel through them.
- [ ] useMultiStateValidator — alike the useStateValidator, but tracks multiple states at a time.
- [x] useMediatedState — like the regular useState but with mediation by custom function. (Implemented as useMediatedState)
- [x] useFirstMountState — check if current render is first. (Implemented as useFirstMountState)
- [x] ~~useRendersCount — count component renders.~~ (Implemented as
useRenderCount). - [x] ~~createGlobalState — cross component shared state.~~ (Not planning to implement)
- [x] ~~useMethods — neat alternative to useReducer.~~ (No plans to implement)
Miscellaneous
- [ ] useEnsuredForwardedRef — use a React.forwardedRef safely.
- [ ] ensuredForwardRef — use a React.forwardedRef safely.
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!
To be clear - not all hooks will be ported, as for me - i'm against of transfering all create* hooks. And its not the only example.
To be clear - not all hooks will be ported, as for me - i'm against of transfering all
create*hooks. And its not the only example.
Definitely! Should we make a list of all the hooks that we don't want ported? Then I can cross them out above. @xobotyi
@JoeDuncko its hard to say rn, im reviewing the hooks on the go and currently refactoring (the full cycle refactoring, meaning reimplementing them from the scratch) hooks im currently using at my job, as this is easiest way for me, as i have little expertise in other areas.
useMountedState and useUnmountPromise — track if component is mounted. (Implemented as useIsMounted)
we dont have useUnmountPromise yet
Crossed out the "create" hooks, split up all the lines with "and"s.
Added links to the new useIsomorphicLayoutEffect and useDebounceCallback hooks
Thank you so much for starting this repo and leading this huge migration work! 🍻
Just wondering what the reasoning is for not migrating the create* utilities, and particularly createMemo. In my project, I have a good number of utility functions that loop over very large arrays, so it's important that they are memoised with useMemo. With createMemo I don't have to create hooks with the same signature as the utility functions, so it's really convenient and avoids a lot of duplication (especially since I use TypeScript).
I should add that I can't just turn all of my utility functions into hooks with useMemo inside them, as I use some of them inside loops. I need both the hook and non-hook versions.
This issue should now be up to date FYI.
It'd be nice to know what needs to be done to port a hook over. I'd like to port useCopyToClipboard, but I'm not sure if it needs refactoring.
Should it keep using useSetState? Can useSetState be ported over as-is? It also needs to use useIsMounted instead of useMountedState. What else?
I wouldn't mind helping out with stories/docs so someone with more context could focus on writing/porting the hooks.
@hedgerh it can't be ported as-is since it's dependency (clipboardjs) should be listed as optional depency now (look at useCookie to see how package check implemented). Tbh I don't remember all internals and away from pc, I'll reply to you once I'll reach the laptop.
No rush. Why are these being listed as peerdeps and as optional now?
@hedgerh since very few people need these hooks - there is no need to make everyone to download them.
@xobotyi @JoeDuncko I'm wondering are going to implement the useCustomCompareEffect |useDeepCompareEffect hook?
@Rey-Wang working on it right now, will be published Monday I guess
This issue is now up to date.
@Rey-Wang we now have useCustomCompareEffect and useDeepCompareEffect!
usePreviousDistinct done ✅
usePreviousDistinctdone ✅
I think we are missing this one in the README
EDIT: Made a PR
Can you please re-visit removing createMemo? It's an extremely useful pattern that allows you to share a memoized function across components. https://github.com/streamich/react-use/blob/master/docs/createMemo.md
Hello, I'm first time working on open source projects. I want to start with useError :)
Hello, I finished the useError hook, but I couldn't start the storybook. I'm just wondering if it's a known issue?
yarn run v1.22.18
$ start-storybook -p 6006 --docs --no-manager-cache
info @storybook/react v6.4.22
info
info => Loading presets
info => Serving static files from ././.storybook/public at /
ERR! TypeError: (intermediate value) is not iterable
ERR! at _default (/node_modules/@storybook/builder-webpack4/dist/cjs/preview/iframe-webpack.config.js:73:22)
ERR! at processTicksAndRejections (internal/process/task_queues.js:95:5)
ERR! at async Object.start (/node_modules/@storybook/builder-webpack4/dist/cjs/index.js:91:16)
ERR! at async Promise.all (index 0)
ERR! at async storybookDevServer (/node_modules/@storybook/core-server/dist/cjs/dev-server.js:126:28)
ERR! at async buildDevStandalone (/node_modules/@storybook/core-server/dist/cjs/build-dev.js:115:31)
ERR! at async buildDev (/node_modules/@storybook/core-server/dist/cjs/build-dev.js:161:5)
ERR! TypeError: (intermediate value) is not iterable
ERR! at _default (/node_modules/@storybook/builder-webpack4/dist/cjs/preview/iframe-webpack.config.js:73:22)
ERR! at processTicksAndRejections (internal/process/task_queues.js:95:5)
ERR! at async Object.start (/node_modules/@storybook/builder-webpack4/dist/cjs/index.js:91:16)
ERR! at async Promise.all (index 0)
ERR! at async storybookDevServer (/node_modules/@storybook/core-server/dist/cjs/dev-server.js:126:28)
ERR! at async buildDevStandalone (/node_modules/@storybook/core-server/dist/cjs/build-dev.js:115:31)
ERR! at async buildDev (/node_modules/@storybook/core-server/dist/cjs/build-dev.js:161:5)
@Bailig Yes, Storybook being broken in main is a known issue. Dependabot broke something last week. Will try to fix it today. Sorry about that!
Hey guys,
I'd like to do migration from old react-use, the only remaining bit for me is useBeforeUnload. Do you have some estimation when will be migrated ?
thanks!
This is a relatively easy project to get involved with contributions! Maybe you'd be interested in opening a PR yourself for it?
useBeforeUnload is easily achievable with useEventListener hook
useEventListener(window, 'beforeunload', ()=>{ /* do your stuff here */ })
If we don't plan to implement useBeforeUnload, maybe we should strike it from OP?
surely do, just realized just now (list been made up before useEventListener implementation)
Overall you can make a PR with migration guide for taht hook (have not enough time for that atm)
That being said, maybe there's something to be said for NOT porting this hook if it's so easy to accomplish with useEventListener
I'll mention it in the list later
@ArttuOll could you please make a mention to migration guide about unwilling to implement useBeforeUnload with example from above conversation?