ecomfe / react-hooks Goto Github PK
View Code? Open in Web Editor NEWCollection of react hooks
License: MIT License
Collection of react hooks
License: MIT License
Having some lint errors in demo
folders but is not detected
Top navigation has only one item and is not easy to find, try to add some sections like getting started
or guidelines of internal
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
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
Better to have links in the index table inside home page, links should refer to corresponding document URL
The Document
section of home page should be rewritten to match current solution, docz
is no longer used
RT, tks!
Use official use-immer to replace all internal references
const [items, {remove}] = useArray(dataSource); // dataSource为对象数组
remove(someItem);
以上代码会失败,因为在immer
的作用下都是Proxy
,没办法引用判断相等
react-hooks/packages/request/src/index.ts
Lines 163 to 166 in 8d89a72
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} />
</>;
调试 huse 项目时总是因为格式化报很多lint错误,想了解下你们是如何解决的!!
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
您好~
可不可以加一个新的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;
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?
const comment = useInputValue('');
<Input.TextArea {...comment} />
以上代码会有类型问题
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
这个 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
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.
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:
useSomethingWith([state, setState])
to wrap an existing state tupleuseSomething
hook depending on the previous useSomethingWith
with a local stateAfter this, we can simple introduce useArrayWith
to help us manage global arrays like:
const globalListState = useRecoilState(globalListAtom);
const [globalList, {push, removeAt}] = useArrayWith(globalListState);
比如有一个请求
getData('post', {
params: {} // 请求地址?后面拼接的参数
data: {} // body中的参数
})
这两中参数都要传过去,useRequest 和 useRequestCallback 就没办法区别两种类型的参数,会全部拼接到?后面
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 useRef
s into useLayoutEffect
and ensure they are not storing a callback executed inside render.
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
目前的实现方式如下:
if (previousPropValue !== propValue) {
这样的话当是非primitive的值对比时,是一直不等的。
是否可以添加支持传入propCompare
函数,支持用户自定义对比方式?
是否可以增加支持Suspense
的useRequset
和useRequestCallback
,或者在已有的request的基础上增加一个支持suspense的boolean类型的参数。
testAndtrigger should be wrapped in useCallback?
没有返回正常的tuple,变成一个混合数组了
【immerjs】Since version 6, support for the fallback implementation has to be explicitly enabled by calling enableES5()
在某些时候,我们已经有了一个数组,但要对这个数组做额外的修改(对应derivedState
),但当这个原始数组变化时,我们的额外修改还要保持住。
场景一:
有一个列表,并且可以新增条目,新增的条目会临时放在列表的最上方向。无论列表是否切换页码、排序,新增条目要保持。
场景二:
在无限滚动加载的列表中,删除了某些项,此时再滚动增加新内容后,要依然保持删除的项不会出现。
这种情况下,useDerivedState
是没法用的,因为原始数组变化(翻页、新加载内容)后,就会变成新的数组,原来的新增、删除等操作都没了
所以我们需要一个useComputedArray
,基于一个原始数组,并在内部以“操作”的形式记录对它的修改,无论原始数组怎么变,都可以把“操作”覆盖上去保留
react-use中特意划分了Lifecycles类hook.为什么不考虑添加呢?好处挺多
react-hooks/packages/request/src/index.ts
Lines 104 to 107 in 8d89a72
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>;
}
react-hooks/packages/poll/src/index.ts
Lines 33 to 36 in 8d89a72
Usage:
function useAttentiveInterval(task, time) {
const isActive = useAttention();
time = isActive ? time : -1;
useStableInterval(task, time);
}
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>
)
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.