Overview
GoogleReCaptcha is a component that automatically executes reCAPTCHA when mounted or when its dependencies change. It’s useful when you want to automatically get a reCAPTCHA token without manually calling executeRecaptcha.
Source: src/google-recaptcha.tsx:11
Import
Props
Callback function that receives the reCAPTCHA token. This function is called automatically whenever reCAPTCHA executes.
- token: The reCAPTCHA token string returned by Google
- Can be synchronous or asynchronous (return a Promise)
The action name to pass to reCAPTCHA. This helps you distinguish different user actions in the reCAPTCHA admin console analytics.Examples:
"login", "submit_form", "checkout"Trigger to refresh and re-execute reCAPTCHA. When this value changes, reCAPTCHA will execute again and call
onVerify with a new token.- Can be any type that changes (boolean, string, number)
- Set to
nullto prevent execution - Useful for refreshing tokens or re-validating after form changes
Return Value
The component returns:- A
<div>element with the container ID if using explicit rendering mode nullif not using explicit rendering
Usage Examples
Basic Usage
With Action Name
Refreshing Token on Form Changes
Conditional Execution
Periodic Token Refresh
Behavior
When Component Mounts
- Retrieves
executeRecaptchafrom context viauseGoogleReCaptcha - Executes reCAPTCHA with the specified action
- Calls
onVerifywith the resulting token
When Props Change
The component re-executes reCAPTCHA when any of these props change:actiononVerifyrefreshReCaptcha
Warnings
- If
executeRecaptchais not available (provider not initialized), execution is skipped - If
onVerifyis not provided, a warning is logged in development mode
TypeScript Interfaces
Comparison with useGoogleReCaptcha Hook
| Feature | GoogleReCaptcha Component | useGoogleReCaptcha Hook |
|---|---|---|
| Execution | Automatic on mount/prop changes | Manual control |
| Use case | Fire-and-forget token generation | Complex flows, manual triggers |
| Flexibility | Limited to component lifecycle | Full control |
| Code style | Declarative | Imperative |
GoogleReCaptcha when:
- You want automatic token generation
- Token should refresh based on state changes
- You prefer declarative React patterns
useGoogleReCaptcha when:
- You need manual control over execution timing
- You want to execute reCAPTCHA on user actions (button clicks)
- You need to handle complex validation flows
Related APIs
- GoogleReCaptchaProvider - Required provider component
- useGoogleReCaptcha - Hook for manual control
- withGoogleReCaptcha - HOC for class components
- TypeScript Interfaces - Type definitions