Skip to content

Conversation

@hamo-o
Copy link
Contributor

@hamo-o hamo-o commented Jun 22, 2025

#️⃣ 연관된 이슈>

📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)

StrictMode 에서도 한번만 동작하는 useEffectOnce 훅을 구현합니다.

🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요

Summary by CodeRabbit

  • New Features

    • Introduced a new custom hook for running effects only once under specified conditions.
  • Refactor

    • Updated calendar and login redirect components to use the new effect hook, improving effect execution reliability.
  • Chores

    • Updated the frontend ignore list to exclude all environment variable files from version control.

@coderabbitai
Copy link

coderabbitai bot commented Jun 22, 2025

Walkthrough

A new custom React hook, useEffectOnce, was introduced and exported for use across the frontend. Existing components that previously used standard useEffect hooks for one-time side effects were refactored to utilize this new hook, ensuring their effects execute only once under specified conditions. The .gitignore was also updated to ignore all .env* files.

Changes

File(s) Change Summary
frontend/.gitignore Added .env* pattern to ignore all environment variable files.
frontend/packages/core/src/hooks/useEffectOnce.ts Introduced new useEffectOnce hook for one-time conditional side effects.
frontend/packages/core/src/hooks/index.ts Exported the new useEffectOnce hook.
frontend/apps/client/src/routes/oauth.redirect/calendar/index.tsx Refactored to use useEffectOnce with a memoized callback for cache invalidation and navigation.
frontend/apps/client/src/routes/oauth.redirect/login/index.tsx Refactored to use useEffectOnce with a memoized callback for login mutation on code present.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant useEffectOnce
    participant Callback

    Component->>useEffectOnce: Pass { condition, callback }
    useEffectOnce->>useEffectOnce: Check if condition is true and not yet called
    alt First time and condition met
        useEffectOnce->>Callback: Invoke callback
        Callback-->>useEffectOnce: Complete
    else Already called or condition false
        useEffectOnce-->>Component: Do nothing
    end
Loading

Poem

🐇
A hop, a skip, a single chance,
Effects now run in one-time dance.
With useEffectOnce, we keep things neat,
No extra calls, just one heartbeat.
Ignore those envs, let secrets hide—
Onward, frontend, with rabbit pride!

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@hamo-o hamo-o marked this pull request as ready for review June 23, 2025 00:38
@hamo-o hamo-o requested a review from dioo1461 as a code owner June 23, 2025 00:38
@hamo-o hamo-o added the 🖥️ FE Frontend label Jun 23, 2025
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 (3)
frontend/apps/client/src/routes/oauth.redirect/calendar/index.tsx (1)

12-17: Consider simplifying the async callback pattern.

The current implementation works but wrapping async operations in an IIFE is unnecessarily complex.

Consider this cleaner approach:

-const clearCalendarCache = useCallback(() => {
-  (async () => {
-    await queryClient.invalidateQueries({ queryKey: calendarKeys.all });
-    navigate({ to: '/my-calendar' });
-  })();
-}, [queryClient, navigate]);
+const clearCalendarCache = useCallback(async () => {
+  await queryClient.invalidateQueries({ queryKey: calendarKeys.all });
+  navigate({ to: '/my-calendar' });
+}, [queryClient, navigate]);

However, ensure that the useEffectOnce hook properly handles async callbacks if you make this change.

frontend/packages/core/src/hooks/useEffectOnce.ts (2)

3-6: Consider improving the TypeScript interface.

The current interface restricts callbacks to void return types, but many real-world use cases involve async operations.

Consider this more flexible interface:

 interface UseEffectOnceOptions {
   condition?: boolean;
-  callback: () => void;
+  callback: () => void | Promise<void>;
 }

This would better support the async patterns used in the codebase (like in the calendar component).


8-13: Enhance JSDoc documentation.

The documentation could be more comprehensive about the hook's behavior and StrictMode compatibility.

 /**
- * 
+ * A hook that ensures a callback function runs only once, even in React StrictMode.
+ * 
  * @param options
  * @param options.condition - 콜백을 실행할 조건 (기본값: true)
  * @param options.callback - 한 번만 실행할 콜백 함수. useCallback을 사용하여 메모이제이션하는 것이 좋습니다.
+ * 
+ * @example
+ * ```tsx
+ * const memoizedCallback = useCallback(() => {
+ *   // Your side effect here
+ * }, [dependencies]);
+ * 
+ * useEffectOnce({ 
+ *   condition: someCondition,
+ *   callback: memoizedCallback 
+ * });
+ * ```
  */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac77e68 and fc020ce.

📒 Files selected for processing (5)
  • frontend/.gitignore (1 hunks)
  • frontend/apps/client/src/routes/oauth.redirect/calendar/index.tsx (1 hunks)
  • frontend/apps/client/src/routes/oauth.redirect/login/index.tsx (2 hunks)
  • frontend/packages/core/src/hooks/index.ts (1 hunks)
  • frontend/packages/core/src/hooks/useEffectOnce.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: frontend
🔇 Additional comments (4)
frontend/.gitignore (1)

14-14: LGTM! Standard environment file exclusion.

The addition of .env* pattern properly excludes all environment configuration files from version control, which is a security best practice.

frontend/packages/core/src/hooks/index.ts (1)

2-2: LGTM! Proper hook export.

The export statement correctly follows the existing pattern and makes the new hook available for consumption.

frontend/apps/client/src/routes/oauth.redirect/calendar/index.tsx (1)

19-19: LGTM! Correct usage of useEffectOnce.

The hook is used appropriately with a memoized callback to ensure the effect runs only once on mount.

frontend/apps/client/src/routes/oauth.redirect/login/index.tsx (1)

14-21: LGTM! Excellent usage pattern.

The implementation correctly:

  • Memoizes the callback with proper dependencies
  • Uses a condition to control when the effect should run
  • Follows the recommended pattern for the useEffectOnce hook

Comment on lines +17 to +27
useEffect(() => {
if (condition && !isCalled.current) {
callback();
}

return () => {
if (!isCalled.current) {
isCalled.current = true;
}
};
}, [condition, callback]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix critical logic error in the hook implementation.

The current implementation has a fundamental flaw in the cleanup function logic that breaks the hook's intended behavior.

Issues:

  1. isCalled.current is not set to true immediately after calling the callback
  2. The cleanup function incorrectly sets the flag when the callback wasn't called
  3. This prevents the hook from working correctly with conditional execution

Example of the bug:
If condition is initially false, the effect runs but doesn't call the callback. The cleanup then sets isCalled.current = true, preventing future execution even when condition becomes true.

Apply this fix:

 useEffect(() => {
   if (condition && !isCalled.current) {
+    isCalled.current = true;
     callback();
   }
-
-  return () => {
-    if (!isCalled.current) {
-      isCalled.current = true;
-    }
-  };
 }, [condition, callback]);

This ensures the callback runs only once when the condition is met, which aligns with the hook's purpose and StrictMode compatibility goals.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
if (condition && !isCalled.current) {
callback();
}
return () => {
if (!isCalled.current) {
isCalled.current = true;
}
};
}, [condition, callback]);
useEffect(() => {
if (condition && !isCalled.current) {
isCalled.current = true;
callback();
}
}, [condition, callback]);
🤖 Prompt for AI Agents
In frontend/packages/core/src/hooks/useEffectOnce.ts between lines 17 and 27,
the hook's logic incorrectly sets isCalled.current to true in the cleanup
function even if the callback was not called, causing the callback to never run
when the condition later becomes true. To fix this, set isCalled.current to true
immediately after calling the callback inside the effect, and remove or adjust
the cleanup function so it does not set isCalled.current when the callback was
not executed. This ensures the callback runs only once when the condition is met
as intended.

@hamo-o hamo-o marked this pull request as draft June 25, 2025 03:38
@hamo-o hamo-o closed this Jun 25, 2025
@hamo-o hamo-o deleted the feature/fe/use-effect-once branch June 25, 2025 11:22
@hamo-o
Copy link
Contributor Author

hamo-o commented Jun 25, 2025

기존 StrictMode의 문제를 해결하고자 만든 훅인데, 리액트의 의도와 맞지 않는 것을 발견하여 브랜치를 변경하여 다른 방법으로 해결했습니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🖥️ FE Frontend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants