Skip to content

Commit

Permalink
feat(shared): 新增 useStateWithTrailClear 带尾部自动清理的状态
Browse files Browse the repository at this point in the history
  • Loading branch information
mengxinssfd committed Aug 28, 2023
1 parent b2f9033 commit 0dc1bef
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/shared/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export * from './useAppendTo';
export * from './useScrollLock';
export * from './useNextEffect';
export * from './useIsChanged';
export * from './useStateWithTrailClear';
25 changes: 25 additions & 0 deletions packages/shared/src/hooks/useStateWithTrailClear.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import React, { useEffect, useState } from 'react';

/**
* 带后续清理的状态
*
* 每当设置一个值,下一次 Effect 就会把它重置为 undefined,
* 也就是说会触发 3 次 effect:
* 1. 外部依赖状态更新
* 2. 依据外部状态更新内部状态
* 3. 内部状态恢复为 undefined
*
* 类似电子打火机的点火装置,点着了气体之后接下来就与点火器无关且可以关掉了。
*/
export function useStateWithTrailClear<T>(
visible: T | undefined,
): ReturnType<typeof React.useState<T>> {
const [state, setState] = useState<typeof visible>();

useEffect(() => {
state !== undefined && setState(undefined);
}, [state]);
useEffect(() => setState(visible), [visible]);

return [state, setState];
}

0 comments on commit 0dc1bef

Please sign in to comment.