0.8.0 • Published 1 year ago

@react-cmpt/hooks v0.8.0

Weekly downloads
3
License
MIT
Repository
github
Last release
1 year ago

React Hooks

Collection of some react hooks

CI npm

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";

const asyncFn = async () => {
  // do something
};

const Demo = ({ asyncFn }) => {
  const { callback, loading } = useAsyncClick(asyncFn);

  return <Button loading={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";

const Demo = () => {
  const [text, setText] = useState("hello");
  const [value] = useDebounce(text, 1000);

  return (
    <div>
      <input
        defaultValue={"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";

const Demo = () => {
  const [value, setValue] = useState();
  // Debounce callback
  const debouncedCallback = useDebouncedCallback(
    // function
    (value) => {
      setValue(value);
    },
    // delay in ms
    1000
  );

  return (
    <div>
      <input onChange={(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";

const asyncFn = async () => {
  // do something
};

const Demo = ({ asyncFn }) => {
  const { callback, loading } = useDebounceClick(asyncFn);

  return <Button loading={loading} click={callback} />;
};

useDeepCompareCache

optiontypedefaultexplain
valueany
import { useDeepCompareCache } from "@react-cmpt/hooks";

const obj1 = { a: 1, b: { b1: 2 } };
const obj2 = { a: 1, b: { b1: 2 } };

const Demo = () => {
  const obj = useDeepCompareCache(obj1);
  console.log(obj1 === obj2); // false
  console.log(obj === obj1); // true
  console.log(obj === obj2); // true

  // ...
};
import { useDeepCompareCache } from "@react-cmpt/hooks";

const Demo = () => {
  // Deep comparison React.useEffect
  useEffect(() => {
    // ...
  }, useDeepCompareCache([A, B]));

  // Deep comparison React.useCallback
  const callback = 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";

const Demo = ({ 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";

const Demo = ({ text }) => {
  const { node, overflow } = useEllipsis(text, { lineClamp: 2 });

  return overflow ? <Tooltip content={text}>{node}</Tooltip> : node;
};

Browser compatibility

-webkit-line-clamp ResizeObserver 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";

const Demo = () => {
  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";

const Demo = () => {
  const getMounted = 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";

const Demo = () => {
  const supportSafeArea = useSupportSafeArea({ postion: "bottom" });

  return (
    <div
      style={{
        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";

const Demo = () => {
  const { imgNode, loading } = useLoadImg({
    src: "[PATH]/demo.jpg",
    style: { width: "100%" },
  });

  return <div data-loading={loading}>{imgNode}</div>;
};

useThrottle

throttled value

returntypeexplain
valueanyReturns the new throttled value.
cancelfunctionThe clear timer function.
callPendingfunctionThe callback manually function.
import { useThrottle } from "@react-cmpt/use-throttle";

const Demo = ({ value }) => {
  const [tValue, { cancel, callPending }] = useThrottle(value, 200);

  // ...
};

useThrottleFn

throttled function

<

returntypeexplain
callbackfunctionThe new throttled function.
cancelfunctionThe clear timer function.
callPendingfunctionThe callback manually function.
import { useThrottleFn } from "@react-cmpt/use-throttle";

const Demo = () => {
  const { callback, cancel, callPending } = useThrottleFn(() => {
    console.log("click");
  }, 200);

  return <button onClick={callback}>++</button>;
};

useUnmount

Unmount callback

optiontypedefaultexplain
fnfunction
import { useUnmount } from "@react-cmpt/hooks";

const Demo = () => {
  useUnmount(() => {
    console.log("Unmount");
  });

  // ...
};

useUpdate

Re-render components

returntypedefaultexplain
rerenderfunctionrerender callback
import { useUpdate } from "@react-cmpt/hooks";

const Demo = () => {
  const rerender = useUpdate();

  return (
    <>
      <div>Date: {Date.now()}</div>
      <button onClick={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";

const Demo = () => {
  useUpdateEffect(() => {
    console.log(value);
  }, [value]);

  // Deep comparison useUpdateEffect
  useUpdateEffect(() => {
    console.log(value);
  }, useDeepCompareCache([value]));

  // ...
};

Dependencies

Dev

# build package
yarn build

# tests
yarn test

# lint
yarn lint

License

MIT

0.8.0

1 year ago

0.8.0-alpha.1

1 year ago

0.8.0-alpha.0

1 year ago

0.7.1

2 years ago

0.7.1-alpha.0

3 years ago

0.7.0

3 years ago

0.6.2

3 years ago

0.6.1

3 years ago

0.6.0

3 years ago

0.5.0

3 years ago

0.4.2

3 years ago

0.4.1

3 years ago