Skip to content

fix: refactor useLayoutEffect to follow React Hook rules and update SSR tests #920

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

deepen-404
Copy link

Summary:
Refactored useLayoutEffect to comply with React's Rules of Hooks and updated the corresponding SSR test.

Changes:

  • Conditional Hook Fix
    Moved isInBrowser() inside useLayoutEffect to avoid conditional hook calls.
  • SSR Optimization
    Introduced isInBrowserEnv for early exit on the server.
  • Test Updates
    Replaced hook call assertion with a check ensuring addChangeListener is not called when isInBrowser returns false.

Outcome:

  • 🛠️ Ensures correct behavior in both browser and server environments.
  • ⚛️ Aligns with React best practices (no hook violations).
  • ✅ Maintains accurate and relevant test coverage.

@deepen-404
Copy link
Author

@eXon Would you be able to review this pull request ?

@eXon
Copy link
Collaborator

eXon commented Apr 15, 2025

Hey @deepen-404,

Thank you for taking the time to create a PR. The reason of the condition on the useLayoutEffect is that it will always stay the same (we're always on the client or server). It means even though it might look like it breaks a rule, we sometimes can bend them ;)

Can you clarify what issue this is addressing? Have you seen any type of unwanted behaviour or warning from this?

@deepen-404
Copy link
Author

Hey @eXon, thanks for the feedback!

You're right that the runtime environment doesn’t change during execution, so in practice this hasn’t caused functional issues. The reason for the change was mainly to align with the Rules of Hooks strictly — even if it works today, conditional hooks can be risky and may lead to confusion or subtle bugs, especially for contributors less familiar with the context.

That said, there wasn’t a specific runtime error or warning prompting this — it was more of a proactive cleanup to make the hook usage explicitly safe and improve test clarity for SSR.

Happy to revert or adjust if we feel it’s unnecessary — let me know what you think!

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