当前进度: 1ee8c72081b3960eed2f730bcac8651cd065a5a0
TypeScript 自带了 DOM 和 ESxxxx 的类型定义,可以在 node_modules/typescript/lib/ 下找到
- !!:cast a var of any type to boolean type
好处:
- callback function object id 唯一
- expensive calc 无需每次 render 都重新计算
疑问:why?
猜测:首先 useRef 不会触发组件 re-render,而 useUpdate 强制组件 re-render(通过使用 useState),所以通过使用 useRef + useUpdate 的组合可以让组件 re-render 的行为变得人为可控。
但是这么做有什么好处呢? 我能想到的唯一好处就是多个 ref 变量修改时可以仅触发一次 re-render。
-
-
✅
useBattery— tracks device battery state.
获取设备实时电量信息 -
✅
useGeolocation— tracks geo location state of user's device.
获取设备实时地理位置信息 -
✅
useHoveranduseHoverDirty— 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, anduseKeyPressEvent— track keys. -
✅
useLocationanduseSearchParam— 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.
获取当前设备的移动信息(三维空间的加速度等,来自于陀螺仪) -
useMouseanduseMouseHovered— 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.
获取元素实时大小(长宽) 使用场景:- 元素随窗口长、宽修改而自适应,如:block 元素的宽度
- 浏览器自身支持 zoom-in/out,此时也会影响 block 元素的宽度
实现方式:
- 给 ReactElement 增加一个隐藏的 iframe 子节点
- 利用父节点的 position: relative 和子节点的 position: absolute + (top-0, left-0, height-100%, width 100%),则子节点的 offsetHeight 和 offsetWidth 即等于父节点的 height 和 width
-
useStartTyping— detects when user starts typing. -
useWindowScroll— tracksWindowscroll position. -
✅
useWindowSize— tracksWindowdimensions.
监听 window.innerHeight/Width 的改变,并用 useRafState 进行了优化 -
✅👍
useMeasure— tracks an HTML element's dimensions using the Resize Observer API.
使用场景是 useSize 的超集,除了可以跟踪元素大小,还有位置
使用方式不同(useSize 是 Higher-Order Component,useMeasue 通过 ref 实现)
实现方式不同 -
createBreakpoint— tracksinnerWidth -
useScrollbarWidth— detects browser's native scrollbars width.
-
-
useAudio— plays audio and exposes its controls.useClickAway— triggers callback when user clicks outside target area.useCss— dynamically adjusts CSS.useDropanduseDropArea— 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.
-
-
useRaf— re-renders component on eachrequestAnimationFrame. -
useIntervalanduseHarmonicIntervalFn— re-renders component on a set interval usingsetInterval. -
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.
强制触发组件更新使用场景:
- ref 作为类的成员变量使用时,其值的修改并不会触发组件更新,使用 useUpdate 可以强制触发组件更新
- ref 作为类的成员变量使用时,其值的修改并不会触发组件更新,使用 useUpdate 可以强制触发组件更新
-
-
useAsync,useAsyncFn, anduseAsyncRetry— resolves anasyncfunction.useBeforeUnload— shows browser alert when user try to reload or close the page.useCookie— provides way to read, update and delete a cookie.useCopyToClipboard— copies text to clipboard.useDebounce— debounces a function.useError— error dispatcher.- ✅
useFavicon— sets favicon of the page.
给 html page 添加 favicon(在 head 中插入 link) useLocalStorage— manages a value inlocalStorage.useLockBodyScroll— lock scrolling of the body element.useRafLoop— calls given function inside the RAF loop.useSessionStorage— manages a value insessionStorage.useThrottleanduseThrottleFn— throttles a function.- ✅
useTitle— sets title of the page.
更新 page title usePermission— query permission status for browser APIs.
-
- ✅
useEffectOnce— a modifieduseEffecthook that only runs once.
useEffect 的语义级封装 - ✅
useEvent— subscribe to events.
注册 event handler - ✅
useLifecycles— callsmountandunmountcallbacks.
useEffect 的语义级封装 - ✅
useMountedStateanduseUnmountPromise— 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— callsmountcallbacks.
useEffect 的语义级封装 - ✅
useUnmount— callsunmountcallbacks.
useEffect 的语义级封装 - ✅
useUpdateEffect— run aneffectonly on updates.
useEffect 的语义级封装。仅当 update 时触发的 effect,mount/unmount 时均不触发 - ✅
useIsomorphicLayoutEffect—useLayoutEffectthat does not show warning when server-side rendering.
window 对象存在时,使用 useLayoutEffect;不存在时,使用 useEffect - ✅
useDeepCompareEffect,useShallowCompareEffect, anduseCustomCompareEffect— run aneffectdepending on deep comparison of its dependencies
- ✅
-
createMemo— factory of memoized hooks.- ✅👍
createReducer— factory of reducer hooks with custom middleware.
可以给 local reducer 添加 middleware
❓ 代码还没有完全看懂消化 createReducerContextandcreateStateContext— factory of hooks for a sharing state between components.useDefault— returns the default value when state isnullorundefined.- ✅
useGetSet— returns state getterget()instead of raw state.
为一个变量增加 getter and setter useGetSetState— as ifuseGetSetanduseSetStatehad a baby.usePrevious— returns the previous state or props.usePreviousDistinct— likeusePreviousbut with a predicate to determine ifpreviousshould update.useObservable— tracks latest value of anObservable.- ✅
useRafState— createssetStatemethod which only updates afterrequestAnimationFrame.
使用 requestAnimationFrame 对 setState 进行优化。
使用场景:对高频更新事件的监听,如:window.resize useSetState— createssetStatemethod which works likethis.setState.useStateList— circularly iterates over an array.- ✅
useToggleanduseBoolean— tracks state of a boolean.
对单个布尔变量及其操作的封装。 - ✅
useCounteranduseNumber— tracks state of a number.
对 Counter 类数值变量及其操作的封装 - ✅
useListand— tracks state of an array.useUpsert
对 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 theuseStateValidator, but tracks multiple states at a time.useMediatedState— like the regularuseStatebut with mediation by custom function.- ✅
useFirstMountState— check if current render is first.
想不到使用场景 useRendersCount— count component renders.createGlobalState— cross component shared state.useMethods— neat alternative touseReducer.
-
useEnsuredForwardedRefandensuredForwardRef— use a React.forwardedRef safely.
Usage — how to import.
Unlicense — public domain.
Support — add yourself to backer list below.