Skip to content

Repository files navigation

React Hooks

Collection of some react hooks

CInpm

Usage

Installation

yarn add @react-cmpt/hooks

Hooks

useAsyncClick

Click event with loading

optiontypedefaultexplain
asyncFuncfunctionasync function
initStateObject{ loading: false }initial loading
returntypedefaultexplain
callbackfunction
loadingboolean
errorErrorcatch error
import{useAsyncClick}from"@react-cmpt/hooks";constasyncFn=async()=>{// do something};constDemo=({ asyncFn })=>{const{ callback, loading }=useAsyncClick(asyncFn);return<Buttonloading={loading}click={callback}/>;};

useDebounce

optiontypedefaultexplain
valueany
delaynumber
optionsObject

options:

optiontypedefaultexplain
maxWaitnumberDescribes the maximum time func is allowed to be delayed before it's invoked
leadingbooleanThis param will execute the function once immediately when called. Subsequent calls will be debounced until the timeout expires.
equalityFnfunctionComparator function which shows if timeout should be started

more options

import{useDebounce}from"@react-cmpt/hooks";constDemo=()=>{const[text,setText]=useState("hello");const[value]=useDebounce(text,1000);return(<div><inputdefaultValue={"hello"}onChange={(e)=>{setText(e.target.value);}}/><p>Actual value: {text}</p><p>Debounce value: {value}</p></div>);};

useDebouncedCallback

optiontypedefaultexplain
callbackfunction
delaynumber
optionsObject
import{useDebouncedCallback}from"@react-cmpt/hooks";constDemo=()=>{const[value,setValue]=useState();// Debounce callbackconstdebouncedCallback=useDebouncedCallback(// function(value)=>{setValue(value);},// delay in ms1000);return(<div><inputonChange={(e)=>debouncedCallback(e.target.value)}/><p>Debounced value: {value}</p></div>);};

useDebouncedClick

Click event with loading and debounce

optiontypedefaultexplain
asyncFuncfunctionasync function
delaynumber0useDebouncedCallbackArgs["delay"]
optionsObjectuseDebouncedCallbackArgs["options"]
returntypedefaultexplain
callbackfunction
loadingboolean
cancelDebouncedCallbackfunctionuseDebouncedCallbackReturns["cancelDebouncedCallback"]
callPendingfunctionuseDebouncedCallbackReturns["callPending"]
errorErrorcatch error
import{useDebouncedClick}from"@react-cmpt/hooks";constasyncFn=async()=>{// do something};constDemo=({ asyncFn })=>{const{ callback, loading }=useDebounceClick(asyncFn);return<Buttonloading={loading}click={callback}/>;};

useDeepCompareCache

optiontypedefaultexplain
valueany
import{useDeepCompareCache}from"@react-cmpt/hooks";constobj1={a: 1,b: {b1: 2}};constobj2={a: 1,b: {b1: 2}};constDemo=()=>{constobj=useDeepCompareCache(obj1);console.log(obj1===obj2);// falseconsole.log(obj===obj1);// trueconsole.log(obj===obj2);// true// ...};
import{useDeepCompareCache}from"@react-cmpt/hooks";constDemo=()=>{// Deep comparison React.useEffectuseEffect(()=>{// ...},useDeepCompareCache([A,B]));// Deep comparison React.useCallbackconstcallback=useCallback(()=>{// ...},useDeepCompareCache([A,B]));// ...};

useDeepEffect

Deep comparison React.useEffect

optiontypedefaultexplain
effectfunctionImperative function that can return a cleanup function
depsArrayIf present, effect will only activate if the values in the list change.
import{useDeepEffect}from"@react-cmpt/hooks";constDemo=({value: Object})=>{useDeepEffect(()=>{// do something},[value]);// ...};

useEllipsis

Hidden overflow content and get overflow status

optiontypedefaultexplain
contentReactNode-Overflow content. The expectation is String
options.lineClampnumber | string-The -webkit-line-clamp CSS property
options.debouncedWaitnumber500The number of milliseconds to delay. useDebouncedCallback
options.wrapperClassNamestring-Wrapper element className
options.wrapperStyleObject-Wrapper element style
options.wrapperPropsObject-Wrapper element other props
options.defaultOverflowboolean-Default value of overflow (returns)
returntypedefaultexplain
nodeJSX.ElmentRender element
overflowbooleanfalseWhether overflow content
reObserveElementfunctionManual re-observe wrapper element
recalculateEllipsisfunctionRecalculate overflow content status
import{useEllipsis}from"@react-cmpt/hooks";constDemo=({ text })=>{const{ node, overflow }=useEllipsis(text,{lineClamp: 2});returnoverflow ? <Tooltipcontent={text}>{node}</Tooltip> : node;};

Browser compatibility

-webkit-line-clampResizeObserver API

useInterval

Handle the setInterval timer function.

optiontypedefaultexplain
fnfunction-Handle function. (setInterval callback)
delaynumber-setInterval ms.
options.autorunbooleantrueRuns automatically when mounted
returntypedefaultexplain
stateidle, runningidleOperating status.
cancelfunctionThe clear timer function.
runfunctionManual restart interval function.
import{useInterval}from"@react-cmpt/hooks";constDemo=()=>{const{ state, cancel, run }=useInterval(()=>{console.log("hi");},1000);// ...};

useMountedState

Check component mount state

optiontypedefaultexplain
----
returntypedefaultexplain
callbackfunctionGet mount status
import{useMountedState}from"@react-cmpt/hooks";constDemo=()=>{constgetMounted=useMountedState();useEffect(()=>{setTimeout(()=>{if(getMounted()){// do...}},1000);},[]);// ...};

useSupportSafeArea

optionstypedefaultexplain
defaultStateboolean-default return bool
position'top' | 'left' | 'right' | 'bottom'topsafe-area-inset-[postion]
import{useLoadImg}from"@react-cmpt/hooks";constDemo=()=>{constsupportSafeArea=useSupportSafeArea({postion: "bottom"});return(<divstyle={{paddingBottom: supportSafeArea ? `env(safe-area-inset-bottom)` : "16px",}}>
footer
</div>);};

constant or env

:root {
@supports (top:constant(safe-area-inset-top)) {
--safe-area-inset-top:constant(safe-area-inset-top);
--safe-area-inset-right:constant(safe-area-inset-right);
--safe-area-inset-bottom:constant(safe-area-inset-bottom);
--safe-area-inset-left:constant(safe-area-inset-left);
}
@supports (top:env(safe-area-inset-top)) {
--safe-area-inset-top:env(safe-area-inset-top);
--safe-area-inset-right:env(safe-area-inset-right);
--safe-area-inset-bottom:env(safe-area-inset-bottom);
--safe-area-inset-left:env(safe-area-inset-left);
}
}
.demo {
padding-bottom:16px;
&[data-supportSafeArea="true"] {
padding-bottom:var(--safe-area-inset-bottom);
}
}

useLoadImg

Get image loading status

optiontypedefaultexplain
srcstring<img /> src
reqLoadingbooleanrequest loading
classNamestring
styleObject
imgPropsObject<img /> props
lazynumber0Delay of done state
returntypedefaultexplain
imgNodeJSX.Element<img />
stateloading, done, error, idleidleimage state
loadingboolean
isErrorbooleanimage errored
import{useLoadImg}from"@react-cmpt/hooks";constDemo=()=>{const{ imgNode, loading }=useLoadImg({src: "[PATH]/demo.jpg",style: {width: "100%"},});return<divdata-loading={loading}>{imgNode}</div>;};

useThrottle

throttled value

optiontypedefaultexplain
valueany-The value to throttle.
waitnumber0The number of milliseconds to throttle invocations to.
optionsleadingboolean-Specify invoking on the leading edge of the timeout.
customizerfunction-The function to customize comparisons.
returntypeexplain
valueanyReturns the new throttled value.
cancelfunctionThe clear timer function.
callPendingfunctionThe callback manually function.
import{useThrottle}from"@react-cmpt/use-throttle";constDemo=({ value })=>{const[tValue,{ cancel, callPending }]=useThrottle(value,200);// ...};

useThrottleFn

throttled function

<

optiontypedefaultexplain
fnfunction-The function to throttle.
waitnumber0The number of milliseconds to throttle invocations to.
optionsleadingboolean-Specify invoking on the leading edge of the timeout.
returntypeexplain
callbackfunctionThe new throttled function.
cancelfunctionThe clear timer function.
callPendingfunctionThe callback manually function.
import{useThrottleFn}from"@react-cmpt/use-throttle";constDemo=()=>{const{ callback, cancel, callPending }=useThrottleFn(()=>{console.log("click");},200);return<buttononClick={callback}>++</button>;};

useUnmount

Unmount callback

optiontypedefaultexplain
fnfunction
import{useUnmount}from"@react-cmpt/hooks";constDemo=()=>{useUnmount(()=>{console.log("Unmount");});// ...};

useUpdate

Re-render components

returntypedefaultexplain
rerenderfunctionrerender callback
import{useUpdate}from"@react-cmpt/hooks";constDemo=()=>{constrerender=useUpdate();return(<><div>Date: {Date.now()}</div><buttononClick={rerender}>Update</button></>);};

useUpdateEffect

React.useEffect cancel the first mount trigger

optiontypedefaultexplain
effectfunctionImperative function that can return a cleanup function
depsArrayIf present, effect will only activate if the values in the list change.
import{useUpdateEffect,useDeepCompareCache}from"@react-cmpt/hooks";constDemo=()=>{useUpdateEffect(()=>{console.log(value);},[value]);// Deep comparison useUpdateEffectuseUpdateEffect(()=>{console.log(value);},useDeepCompareCache([value]));// ...};

Dependencies

Dev

# build package
yarn build
# tests
yarn test# lint
yarn lint

License

MIT

About

Some react hooks

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages