Giter Site home page Giter Site logo

react-hooks's People

Contributors

599316527 avatar bdwenxi avatar buptlhuanyu avatar codezyb avatar colmugx avatar feibinyang avatar hunter2009 avatar ice-zjchen avatar laughsun0513 avatar leuisken avatar nick-chenze avatar otakustay avatar qiaoyuwen avatar sunny-117 avatar susiwen8 avatar symind avatar tonyjeffrey avatar yixiaojiu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-hooks's Issues

Problems in current doc implementation

  1. Having some lint errors in demo folders but is not detected

    image

  2. Top navigation has only one item and is not easy to find, try to add some sections like getting started or guidelines of internal

    image

  3. Some packages have multiple hooks exports but in side navigation only a single link is presented, we'd better split them into standalone markdown files

    image

  4. Title of hooks composed with multiple words are renders in a strange naming conventions (Foo-bar), we'd like to see a form like Foo Bar

    image

  5. Better to have links in the index table inside home page, links should refer to corresponding document URL

    image

  6. The Document section of home page should be rewritten to match current solution, docz is no longer used

    image

Expose `request` in result of `useRequest` as well

const resultFixedForEffect: RequestResult<O, E> = {
...result,
pending: result.pendingCount === undefined ? true : result.pending,
};

Expacted:

 const resultFixedForEffect = {
      ...result,
      pending: result.pendingCount === undefined ? true : result.pending,
+     request,
 };

So that I can trigger request automatically as well as manually.

const {pending, data: tasks, request: reload} = useRequest(getTasks, {status});
return <>
   <button onClick={reload}>Refresh</button>
   <List loading={pending} items={tasks} />
</>;

[Feature] useDebouncedCallback add 'cleanUp' function as params

I have noticed that useDebouncedCallback doesn't have independent 'cleanUp' function. It uses clear function which should attach to debouncedCallback. Also I have notice there is unused interface DebouncedFunction, it seems to me that useDebouncedCallback had some plan for it.

So I propose something like this

function useDebouncedCallback<C extends Function>(
    options: {
        callback: C;
        clear?: () => void;
    },
    wait: number
): C

If I miss something, or this was intentional, just give a heads up. If you agreed, I'll be happy to make a PR for it.

Thanks

useDomPurify

您好~

可不可以加一个新的hook,用于处理html字符串并防止XSS攻击

下面的实现会带来一个问题:引入dompurify这个第三方的dependencies,如果自己去实现dompurify这个确实有些成本,不知您这边有什么好的建议吗?

import {useMemo} from 'react';
import createDomPurify from 'dompurify';

const domPurify = createDomPurify(window);

const useDomPurify = function (html: string = ''): string {
    return useMemo<string>(
        function () {
            return domPurify.sanitize(html);
        },
        [html]
    );
};

export default useDomPurify;

Add a useToggleOrSet for convenience?

Now:

const [show, toggle] = useToggle(false);
const [show, on, off, toggle] = useSwitch(false); // not use var off

Expect:

const [show, toggle] = useToggleOrSet(false);
toggle(); // toggle the prevState
toggle(true); // change the state to true ===  on
toggle(false); // change the state to false === off

maybe like this?

useInfiniteScroll call loadMore twice in some case.

In my case, there is a InfiniteScroll component using useInfiniteScroll hook with {initialLoad: true} option. When entering this page with no scrollTop in last page, everything is ok, but if the scrollTop was not zero in last page, onscroll event will trigger, and with {initialLoad: true} option, the loadMore function will be called twice.

I create this patch in my local environment, and if this patch is approve, I'll then create a pull request.

diff --git a/packages/infinite-scroll/src/index.ts b/packages/infinite-scroll/src/index.ts
index cce41e8..bf58e50 100644
--- a/packages/infinite-scroll/src/index.ts
+++ b/packages/infinite-scroll/src/index.ts
@@ -55,15 +55,19 @@ export function useInfiniteScroll<T>(
         createContextReducers<T>(),
         {pendingCount: 0, dataSource: initialItems, hasMore: true}
     );
+    const loading = !!pendingCount;
     const loadMore = useCallback(
         async () => {
+            if (loading) {
+                return;
+            }
             initialLoadStarted.current = true;
             requestStart();
             const response = await fetch({offset: dataSource.length});
             initialLoadEnded.current = true;
             requestEnd(response);
         },
-        [requestStart, fetch, dataSource.length, requestEnd]
+        [loading, requestStart, fetch, dataSource.length, requestEnd]
     );
     useEffect(
         () => {
@@ -78,7 +82,7 @@ export function useInfiniteScroll<T>(
         dataSource,
         loadMore,
         hasMore,
-        loading: !!pendingCount,
-        initialLoading: initialLoad && !initialLoadEnded.current && !!pendingCount,
+        loading,
+        initialLoading: initialLoad && !initialLoadEnded.current && loading,
     };
 }

useOnScreenCallback 返回的 ref 不能获取 ref.current 么

问题:使用 useOnScreenCallback 这个 hook 返回的 ref,赋值给 DOM 元素后,ref.current 不能获取到 DOM。但在使用中会有需要获取这个 DOM 进行操作的情景(比如 add/remove classList 来显示动画);

期望:希望赋值完 ref={ref} 后,ref.current 可以获取 DOM 结构,这样可以在 callback 里直接进行后续操作。

参考 demo:https://codesandbox.io/s/heuristic-haslett-s1qs8?fontsize=14&hidenavigation=1&theme=dark

Sync function support in useActionPending

useActionPending actually supports sync function inside its implement except the pendingCount state can be incremented and decremented without any meaningful case, the unexpected change of pendingCount can cause a performance dropdown sometimes.

In case developers are not aware of the function's async or not, it is better for useActionPending to be compatible with both, reducing unexpected change of pendingCount state by examining function's return value.

@ice-zjchen

Adopt variant underlying state management

Pick useArray as an example, this hook creates a bunch of convenient functions around Array types, it manages a local state by using useState in its implementation:

const [list, {push, removeAt}] = useArray();

<CreateForm onSubmit={push} />
<DeleteButton onClick={index => removeAt(index)} />

In real word, we often create states from variant sources, like recoil's useRecoilState, or a abstract [state, setState] passed via Context, then we are not able to create array functions around these states, this is an important missing functionality of a well designed hooks library.

For this reason, we're preparing to split some hooks into 2 parts:

  1. a useSomethingWith([state, setState]) to wrap an existing state tuple
  2. a useSomething hook depending on the previous useSomethingWith with a local state

After this, we can simple introduce useArrayWith to help us manage global arrays like:

const globalListState = useRecoilState(globalListAtom);
const [globalList, {push, removeAt}] = useArrayWith(globalListState);

Carefully review all cases of useRef

According to this issue, for what I understand, concurrent mode can have 2 copies of component, one is committed to DOM and one is a in memory snapshot.

The problem is that the uncommitted version may run render with a older version of props and states, so update refs inside render can break the consistency of component's surface.

Having usePreviousValue as an example:

const App = props => {
  const previous = usePreviousValue(props.value);
  return `${previous} -> ${value}`;
};

What if App is rendered with props.value as "foo" and then "bar" and then "foo" again, it should render bar -> foo from the last commit, however when in memory version renders it with a previous "foo" as props.value, the ref inside usePreviousValue got updated to "foo", running the committed version later results in foo -> foo, which is absolutely incorrect.

So we may have to move all useRefs into useLayoutEffect and ensure they are not storing a callback executed inside render.

previous-value

These are just my two cents
I have issues with the naming.
For example - use previous value - but actually it mutates the value. So are the other functions.
useOriginalDeepCopy actually does regular copy

useDerivedState支持传入自定义props对比方法

目前的实现方式如下:

if (previousPropValue !== propValue) {

这样的话当是非primitive的值对比时,是一直不等的。

是否可以添加支持传入propCompare函数,支持用户自定义对比方式?

request in Suspense

是否可以增加支持SuspenseuseRequsetuseRequestCallback,或者在已有的request的基础上增加一个支持suspense的boolean类型的参数。

Clickoutside

testAndtrigger should be wrapped in useCallback?

Add a computed array hook

在某些时候,我们已经有了一个数组,但要对这个数组做额外的修改(对应derivedState),但当这个原始数组变化时,我们的额外修改还要保持住。

场景一:

有一个列表,并且可以新增条目,新增的条目会临时放在列表的最上方向。无论列表是否切换页码、排序,新增条目要保持。

场景二:

在无限滚动加载的列表中,删除了某些项,此时再滚动增加新内容后,要依然保持删除的项不会出现。

这种情况下,useDerivedState是没法用的,因为原始数组变化(翻页、新加载内容)后,就会变成新的数组,原来的新增、删除等操作都没了

所以我们需要一个useComputedArray,基于一个原始数组,并在内部以“操作”的形式记录对它的修改,无论原始数组怎么变,都可以把“操作”覆盖上去保留

Need promise associated with `request` of `useRequestCall` to track task status outside

task(key).then(
data => receive(key, data),
ex => error(key, ex)
);

Usage:

function DeleteButton ({segmentId, refresh}) {
    const [delete, {pending}] = useRequestCallback(deleteSegment, {segmentId});
    const onClick = async () => {
        if (await confirm(message)) {
            await delete();  // <--- promise to be awaited to ensure task is settled.
            refresh();
        }
    };
    return <button disabled={pending} onClick={onClick}>删除</button>;
}

Separate `useAttention` from `usePoll` for more combinations

export function usePoll<S>(fetch: () => Promise<S>, options: number | PollOptions): PollHook<S> {
const {minInterval, maxInterval, maxIdleTime, stopOnInactive} = resolveOptions(options);
const attention = useRef<AttentionContext | null>(null);
const lastAttentionState = useRef<AttentionState>('active');

Usage:

function useAttentiveInterval(task, time) {
     const isActive = useAttention();
     time = isActive ? time : -1;
     useStableInterval(task, time);
}

【Feature Request】support max、min、step option in useCounter

when i use a component like steps which has a index prop named current, the code will like

const App = () => {
    const [current, {inc, dec}] = useConter(0, {max: 3});

    return (
         // steps with three items
        <Steps current={current} />
        <button onClick={inc}>next</button>
        <button onClick={dec}>previous</button>
    )
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.