Skip to content

Conversation

@zombieJ
Copy link
Member

@zombieJ zombieJ commented Nov 5, 2025

Summary by CodeRabbit

发布说明

  • 重构
    • 改进了 useEvent Hook 的类型系统与返回行为,支持可选回调并提高类型安全与调用灵活性。
  • 测试
    • 新增针对 useEvent 的类型覆盖测试,验证可选与必需回调场景的行为一致性与稳定性。

@vercel
Copy link

vercel bot commented Nov 5, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
util Ready Ready Preview Comment Nov 5, 2025 7:43am

@gemini-code-assist
Copy link

Summary of Changes

Hello @zombieJ, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refines the useEvent React hook by introducing explicit type support for an undefined callback. This change improves the hook's robustness and type safety, allowing developers to pass optional event handlers without encountering type errors, thereby making the hook more adaptable to various use cases where a callback might not always be present.

Highlights

  • Type Definition Update: The useEvent hook's callback parameter now explicitly supports undefined as a valid input type, enhancing flexibility for optional handlers.
  • Internal Ref Type Adjustment: The fnRef useRef now correctly types its current value as T | undefined to align with the updated callback signature, improving internal type consistency.
  • Callback Return Type Clarity: The memoFn useCallback now includes an explicit type assertion to T for its returned function, ensuring type consistency and preventing potential type inference issues.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Nov 5, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

useEvent 钩子的泛型与参数类型扩展为允许 undefined 回调,调整内部 ref 类型与 useCallback 的类型推导;新增针对该钩子的类型测试以验证用例(无运行时行为改动)。

Changes

内聚组 / 文件(s) 变更摘要
useEvent 钩子类型更新
src/hooks/useEvent.ts
将泛型约束从 Function 细化为 (...args: any[]) => any | undefinedcallback 参数接受 `T
测试:添加类型覆盖用例
tests/hooks.test.tsx
导入并新增 useEvent 的类型/用法测试(组件内对可选与必需回调的调用),不改变运行时逻辑,仅增加类型层面的覆盖。

Sequence Diagram(s)

sequenceDiagram
  participant C as Component
  participant H as useEvent hook
  participant R as fnRef
  participant M as memoizedFn

  C->>H: 提供 callback (可能为 undefined)
  H->>R: 初始化 / 更新 `fnRef.current = callback`
  H->>M: 返回 memoizedFn
  C->>M: 调用 memoizedFn(...args)
  M->>R: 读取 `fnRef.current`
  alt fnRef.current 存在
    R->>R: 执行 `fnRef.current(...args)`
  else fnRef.current undefined
    note right of R `#f8f3d7`: 使用可选链,静默返回 undefined
  end
Loading

Estimated code review effort

🎯 2 (简单) | ⏱️ ~10 分钟

  • 重点检查项:
    • 验证当 callbackundefined 时运行时路径(可选链)是否满足预期场景。
    • 审核导出签名的条件类型是否与现有调用点兼容,特别是对返回类型的期望(是否会影响类型推断)。
    • 测试 tests/hooks.test.tsx 中新增用例是否覆盖了关键边界(可选与必需回调)。

Poem

🐰 我是爱敲键的兔子,轻嗅着类型的风,
回调可有可无,仍被可选链温柔拥,
泛型变得更精细,推导悄然生效,
小小测试驻足,确保安稳与从容。 🥕

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题明确总结了主要变更:增强 useEvent 钩子的类型系统以支持 undefined 回调,这正是 PR 的核心改动。
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch useEvent-type

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Nov 5, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.28%. Comparing base (10c5697) to head (7eb618d).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #706   +/-   ##
=======================================
  Coverage   90.28%   90.28%           
=======================================
  Files          37       37           
  Lines         885      885           
  Branches      301      293    -8     
=======================================
  Hits          799      799           
  Misses         84       84           
  Partials        2        2           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request aims to add support for an undefined callback in the useEvent hook. The changes to the type constraints and useRef are good improvements. However, there is a significant type safety issue with the return type of the hook. When an undefined callback is passed, the returned function's type does not accurately represent its runtime behavior, which can lead to unexpected errors. My review includes a detailed explanation and a suggested fix to make the hook type-safe.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33ca7f7 and 1d3ddda.

📒 Files selected for processing (1)
  • src/hooks/useEvent.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test / react component workflow
🔇 Additional comments (1)
src/hooks/useEvent.ts (1)

8-8: 改进:ref 类型更加精确

将 ref 类型从 any 改为 T | undefined 并使用 callback 进行初始化是一个很好的改进,提升了类型安全性。

@zombieJ
Copy link
Member Author

zombieJ commented Nov 5, 2025

@gemini-code-assist 请再看一下

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

这个 PR 旨在改进 useEvent hook,使其支持 undefined 回调,这是一个很好的增强。类型定义变得更加精确,这是一个正确的方向。

我在代码中发现了一些可以改进的地方:

  1. useEvent 的实现与其新的类型签名存在一个关键的类型不匹配问题,可能导致编译错误或类型不安全。
  2. useRef 的类型可以简化,使其更清晰。
  3. useCallback 中的参数类型可以更精确,以增强类型安全。
  4. useEvent 添加的测试用例目前只检查编译时类型,建议扩展测试以覆盖运行时的各种场景,确保 hook 的健壮性。

详细的建议请见具体的代码注释。

Comment on lines +711 to +728
describe('useEvent', () => {
it('extract type', () => {
const Demo = (props: {
canUndefined?: (a: number) => boolean;
notUndefined: (a: number) => boolean;
}) => {
const ua = useEvent(props.canUndefined);
const ub = useEvent(props.notUndefined);

ua(1);
ub(2);

return null;
};

expect(Demo).toBeTruthy();
});
});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

这个测试用例目前只在编译时检查类型,通过 expect(Demo).toBeTruthy() 来断言组件定义本身。这并不能验证 useEvent hook 的运行时行为。

建议增加更全面的测试,覆盖以下场景:

  1. 运行时行为:渲染组件,并实际调用 useEvent 返回的函数,断言回调函数是否被正确调用。
  2. 回调更新:测试当 callback prop 变更后,useEvent 返回的函数是否会调用最新的回调。
  3. undefined 场景:测试当传入 undefined 时,调用返回的函数不会抛出错误。

一个更完善的测试可能如下所示:

it('should call the latest function', () => {
  const fn1 = jest.fn();
  const fn2 = jest.fn();

  const Test = ({ cb }: { cb: () => void }) => {
    const eventFn = useEvent(cb);
    return <button onClick={eventFn}>Click</button>;
  };

  const { getByText, rerender } = render(<Test cb={fn1} />);
  fireEvent.click(getByText('Click'));
  expect(fn1).toHaveBeenCalledTimes(1);
  expect(fn2).toHaveBeenCalledTimes(0);

  rerender(<Test cb={fn2} />);
  fireEvent.click(getByText('Click'));
  expect(fn1).toHaveBeenCalledTimes(1);
  expect(fn2).toHaveBeenCalledTimes(1);
});

it('should not throw error when callback is undefined', () => {
  const Test = ({ cb }: { cb?: () => void }) => {
    const eventFn = useEvent(cb);
    return <button onClick={eventFn}>Click</button>;
  };

  const { getByText } = render(<Test cb={undefined} />);
  expect(() => {
    fireEvent.click(getByText('Click'));
  }).not.toThrow();
});

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/hooks.test.tsx (1)

711-728: 建议增强测试以验证运行时行为。

当前测试主要验证类型编译正确性,但缺少运行时行为验证。建议添加以下测试场景:

  1. 验证当 canUndefined 实际为 undefined 时,调用 ua() 返回 undefined
  2. 验证当 canUndefined 为函数时,调用 ua() 返回正确的结果
  3. 验证 notUndefined 的调用行为

可以改进为:

  describe('useEvent', () => {
    it('extract type', () => {
      const Demo = (props: {
        canUndefined?: (a: number) => boolean;
        notUndefined: (a: number) => boolean;
      }) => {
        const ua = useEvent(props.canUndefined);
        const ub = useEvent(props.notUndefined);

-       ua(1);
-       ub(2);
+       const resultA = ua(1);
+       const resultB = ub(2);

        return null;
      };

-     expect(Demo).toBeTruthy();
+     const { rerender } = render(<Demo notUndefined={x => x > 0} />);
+     
+     // Test with canUndefined as a function
+     rerender(<Demo canUndefined={x => x > 5} notUndefined={x => x > 0} />);
+     
+     // Test with canUndefined as undefined  
+     rerender(<Demo canUndefined={undefined} notUndefined={x => x > 0} />);
    });
  });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1d3ddda and 7eb618d.

📒 Files selected for processing (2)
  • src/hooks/useEvent.ts (1 hunks)
  • tests/hooks.test.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: test / react component workflow
  • GitHub Check: test / react component workflow
🔇 Additional comments (3)
tests/hooks.test.tsx (1)

12-12: 导入语句正确。

新增的 useEvent 导入语句符合测试需求。

src/hooks/useEvent.ts (2)

15-18: 移除类型断言是好的,但需确保类型匹配。

相比旧代码的 as T 断言,当前实现移除了强制类型转换,这提高了类型安全性。可选链 ?. 的使用也是正确的,可以安全处理 undefined 回调。

但如上一条评论所述,可选链会导致返回类型包含 | undefined,这与条件返回类型(当 T 为确定函数时应返回 T)可能存在不匹配。如果 TypeScript 编译通过,可能是由于 any 类型的存在。

建议在修复 ref 类型后,验证是否需要类型断言来匹配条件返回类型。


12-13: 简化 ref 的类型定义。

当前 ref 被类型化为 T | undefined,但 callback 参数本身就是 T。当 T 已经包含 undefined(如 T = Func | undefined)时,T | undefinedT 等价;当 T 是确定的函数时,T | undefined 则引入了不必要的类型扩宽。

建议简化为:

-  const fnRef = React.useRef<T | undefined>(callback);
+  const fnRef = React.useRef<T>(callback);

这样可以:

  1. 避免不必要的类型扩宽
  2. 让类型推断更精确
  3. 使实现与条件返回类型更好地匹配

Likely an incorrect or invalid review comment.

@zombieJ zombieJ merged commit 8a92785 into master Nov 5, 2025
12 checks passed
@zombieJ zombieJ deleted the useEvent-type branch November 5, 2025 07:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants