Skip to content

fix: Prevent Turnstile widget from constantly reloading #142

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

Merged
merged 1 commit into from
Jun 8, 2025

Conversation

nullcoder
Copy link
Owner

Summary

Fixed the issue where the invisible Turnstile widget was constantly reloading due to React re-renders.

Problem

The Turnstile component was re-rendering and recreating the widget whenever the parent component re-rendered. This happened because:

  • Callback functions were recreated on every render
  • The useEffect dependency array included these callbacks
  • Each re-render would destroy and recreate the widget

Solution

Implemented an optimal solution using:

  1. Ref for callbacks - Store callbacks in a ref that's updated without triggering re-renders
  2. isRenderedRef flag - Ensure the widget is only rendered once after script loads
  3. Proper cleanup - Only remove widget on unmount, not on every re-render

This approach:

  • Prevents unnecessary widget reloads
  • Keeps callbacks fresh without stale closures
  • Only re-renders when sitekey, theme, or size changes (expected behavior)

Test Plan

  • Updated tests to verify callbacks are properly forwarded
  • All tests passing
  • Manual testing with real Turnstile widget
  • Verify widget only loads once
  • Confirm callbacks work correctly after parent re-renders

🤖 Generated with Claude Code

- Use refs to store callbacks and avoid re-renders
- Add isRenderedRef to ensure widget is only rendered once
- Keep callbacks up-to-date without triggering re-renders
- Update tests to verify callbacks are properly forwarded

This approach is more optimal as it:
1. Prevents the widget from reloading when parent re-renders
2. Keeps callbacks fresh without stale closures
3. Only re-renders when sitekey, theme, or size changes

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@nullcoder nullcoder merged commit 9c26443 into main Jun 8, 2025
1 check was pending
@nullcoder nullcoder deleted the fix/turnstile-reloading branch June 8, 2025 09:15
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.

1 participant