8000 GitHub - rtxu/react-use: React Hooks — 👍
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

rtxu/react-use

 
 

Repository files navigation



👍
react-use





npm package CircleCI master npm downloads demos
Collection of essential React Hooks. Port of libreact.
Translations: 🇨🇳 汉语




npm i react-use





阅读有感

当前进度: 1ee8c72081b3960eed2f730bcac8651cd065a5a0

TypeScript 自带了 DOM 和 ESxxxx 的类型定义,可以在 node_modules/typescript/lib/ 下找到

Javascript 奇技淫巧

  1. !!:cast a var of any type to boolean type

常见 Pattern

使用 useMemo 确保尽可能返回 memorized value

好处:

  1. callback function object id 唯一
  2. expensive calc 无需每次 render 都重新计算

使用 useRef + useUpdate 代替 useState

疑问:why?
猜测:首先 useRef 不会触发组件 re-render,而 useUpdate 强制组件 re-render(通过使用 useState),所以通过使用 useRef + useUpdate 的组合可以让组件 re-render 的行为变得人为可控。

但是这么做有什么好处呢? 我能想到的唯一好处就是多个 ref 变量修改时可以仅触发一次 re-render。

  • Sensors

    • useBattery — tracks device battery state.
      获取设备实时电量信息

    • useGeolocation — tracks geo location state of user's device.
      获取设备实时地理位置信息

    • useHover and useHoverDirty — tracks mouse hover state of some element.
      获取鼠标当前是否悬停(hover)在当前组件上

    • useIdle — tracks whether user is being inactive.
      根据监听用户输入事件(mousedown/mousemove/keydown/resize/touchstart/wheel),判断当前用户是否处于 idle 状态。

    • useIntersection — tracks an HTML element's intersection.

    • useKey, useKeyPress, useKeyboardJs, and useKeyPressEvent — track keys.

    • useLocation and useSearchParam — tracks page navigation bar location state.
      获取浏览器地址栏内容和地址 History

    • useLongPress — tracks long press gesture of some element.

    • useMedia — tracks state of a CSS media query.
      获取一个 media query 的实时结果

    • useMediaDevices — tracks state of connected hardware devices.
      获取当前本机的媒体设备信息(如:摄像头、麦克风等)

    • useMotion — tracks state of device's motion sensor.
      获取当前设备的移动信息(三维空间的加速度等,来自于陀螺仪)

    • useMouse and useMouseHovered — tracks state of mouse position.

    • useNetwork — tracks state of user's internet connection.
      获取当前设备的网络连接情况(连接类型:bluetooth/cellular/ethernet/none/wifi、是否在线、下载速率、rtt 等)
      实验性 feature,浏览器支持并不好

    • useOrientation — tracks state of device's screen orientation.
      获取当前屏幕方向

    • usePageLeave — triggers when mouse leaves page boundaries.
      当鼠标离开页面区域时,触发 handler

    • useScroll — tracks an HTML element's scroll position.

    • useScrolling — tracks whether HTML element is scrolling.

    • ✅👍 useSize — tracks an HTML element's size.
      获取元素实时大小(长宽) 使用场景:

      1. 元素随窗口长、宽修改而自适应,如:block 元素的宽度
      2. 浏览器自身支持 zoom-in/out,此时也会影响 block 元素的宽度

      实现方式:

      1. 给 ReactElement 增加一个隐藏的 iframe 子节点
      2. 利用父节点的 position: relative 和子节点的 position: absolute + (top-0, left-0, height-100%, width 100%),则子节点的 offsetHeight 和 offsetWidth 即等于父节点的 height 和 width
    • useStartTyping — detects when user starts typing.

    • useWindowScroll — tracks Window scroll position.

    • useWindowSize — tracks Window dimensions.
      监听 window.innerHeight/Width 的改变,并用 useRafState 进行了优化

    • ✅👍 useMeasure — tracks an HTML element's dimensions using the Resize Observer API.
      使用场景是 useSize 的超集,除了可以跟踪元素大小,还有位置
      使用方式不同(useSize 是 Higher-Order Component,useMeasue 通过 ref 实现)
      实现方式不同

    • createBreakpoint — tracks innerWidth

    • useScrollbarWidth — detects browser's native scrollbars width.

  • UI

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

    • useUpdate — returns a callback, which re-renders component when called.
      强制触发组件更新

      使用场景:

      1. ref 作为类的成员变量使用时,其值的修改并不会触发组件更新,使用 useUpdate 可以强制触发组件更新

  • Side-effects

  • Lifecycles

    • useEffectOnce — a modified useEffect hook that only runs once.
      useEffect 的语义级封装
    • useEvent — subscribe to events.
      注册 event handler
    • useLifecycles — calls mount and unmount callbacks.
      useEffect 的语义级封装
    • useMountedState and useUnmountPromise — track if component is mounted.
      想不到使用场景
    • usePromise — resolves promise only while component is mounted.
      想不到使用场景
    • useLogger — logs in console as component goes through life-cycles.
      将一个 component 的 mount/umount/update 事件 log 下来,供调试时使用
    • useMount — calls mount callbacks.
      useEffect 的语义级封装
    • useUnmount — calls unmount callbacks.
      useEffect 的语义级封装
    • useUpdateEffect — run an effect only on updates.
      useEffect 的语义级封装。仅当 update 时触发的 effect,mount/unmount 时均不触发
    • useIsomorphicLayoutEffectuseLayoutEffect that does not show warning when server-side rendering.
      window 对象存在时,使用 useLayoutEffect;不存在时,使用 useEffect
    • useDeepCompareEffect, useShallowCompareEffect, and useCustomCompareEffect — run an effect depending on deep comparison of its dependencies

  • State

    • createMemo — factory of memoized hooks.
    • ✅👍 createReducer — factory of reducer hooks with custom middleware.
      可以给 local reducer 添加 middleware
      ❓ 代码还没有完全看懂消化
    • createReducerContext and createStateContext — factory of hooks for a sharing state between components.
    • useDefault — returns the default value when state is null or undefined.
    • useGetSet — returns state getter get() instead of raw state.
      为一个变量增加 getter and setter
    • useGetSetState — as if useGetSet and useSetState had a baby.
    • usePrevious — returns the previous state or props.
    • usePreviousDistinct — like usePrevious but with a predicate to determine if previous should update.
    • useObservable — tracks latest value of an Observable.
    • useRafState — creates setState method which only updates after requestAnimationFrame.
      使用 requestAnimationFrame 对 setState 进行优化。
      使用场景:对高频更新事件的监听,如:window.resize
    • useSetState — creates setState method which works like this.setState.
    • useStateList — circularly iterates over an array.
    • useToggle and useBoolean — tracks state of a boolean.
      对单个布尔变量及其操作的封装。
    • useCounter and useNumber — tracks state of a number.
      对 Counter 类数值变量及其操作的封装
    • useList and useUpsert — tracks state of an array.
      对 List 类型数据及其操作的封装
    • useMap — tracks state of an object.
      对 Map 类型数据及其操作的封装
    • useSet — tracks state of a Set.
    • useQueue — implements simple queue.
    • 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.
    • useMediatedState — like the regular useState but with mediation by custom function.
    • useFirstMountState — check if current render is first.
      想不到使用场景
    • useRendersCount — count component renders.
    • createGlobalState — cross component shared state.
    • useMethods — neat alternative to useReducer.

  • Miscellaneous








Usage — how to import.
Unlicense — public domain.
Support — add yourself to backer list below.






Contributors








Packages

No packages published

Languages

  • TypeScript 99.5%
  • JavaScript 0.5%
0