React Hook
useProfanityChecker hook for React integration with state management
The useProfanityChecker hook provides stateful profanity checking for React applications with built-in caching, error handling, and performance optimizations.
Hook Signature
const useProfanityChecker = (config?: ProfanityCheckerConfig) => {
result: CheckProfanityResult | null; // Cached last result
checkText: (text: string) => ProfanityCheckResult;
checkTextAsync: (text: string) => Promise<ProfanityCheckResult>;
reset: () => void; // Clear cached state
isDirty: boolean; // True if profanity found
isWordProfane: (word: string) => boolean; // No state update
}State Variables
| Prop | Type | Default |
|---|---|---|
result? | CheckProfanityResult | null | null |
isDirty? | boolean | false |
Methods
| Prop | Type | Default |
|---|---|---|
checkText? | (text: string) => ProfanityCheckResult | N/A |
checkTextAsync? | (text: string) => Promise<ProfanityCheckResult> | N/A |
reset? | () => void | N/A |
isWordProfane? | (word: string) => boolean | N/A |
Form Submission Usage Flow
Initialize the hook with your configuration options.
const { checkText, result, isDirty, reset } = useProfanityChecker({
languages: ['english', 'spanish'],
enableContextAware: true,
autoReplace: true
});Check user input before form submission using checkText().
const handleSubmit = (e) => {
e.preventDefault();
const checkResult = checkText(message);
if (checkResult.containsProfanity) {
// Handle profanity detection
return;
}
// Proceed with clean message
submitMessage(message);
};Handle profanity results by checking result.containsProfanity and displaying warnings.
{result?.containsProfanity && (
<div className="error">
Found inappropriate content: {result.profaneWords.join(', ')}
</div>
)}Reset state when needed using the reset() method to clear cached results.
const clearForm = () => {
setMessage('');
reset(); // Clear profanity check results
};Usage Examples
import React, { useState } from 'react';
import { useProfanityChecker } from 'glin-profanity';
function ChatInput() {
const [message, setMessage] = useState('');
const { checkText, result, isDirty, reset } = useProfanityChecker();
const handleSubmit = (e) => {
e.preventDefault();
const checkResult = checkText(message);
if (checkResult.containsProfanity) {
alert(`Found inappropriate content: ${checkResult.profaneWords.join(', ')}`);
return;
}
console.log('Clean message:', message);
setMessage('');
reset();
};
return (
<form onSubmit={handleSubmit}>
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Type your message..."
className={isDirty ? 'border-red-500' : 'border-gray-300'}
/>
<button type="submit" disabled={isDirty}>
Send Message
</button>
{result?.containsProfanity && (
<div className="text-red-500 text-sm mt-1">
Please remove: {result.profaneWords.join(', ')}
</div>
)}
</form>
);
}import React, { useState } from 'react';
import { useProfanityChecker } from 'glin-profanity';
function AsyncCommentForm() {
const [comment, setComment] = useState('');
const [isChecking, setIsChecking] = useState(false);
const { checkTextAsync, result, isDirty, reset } = useProfanityChecker({
languages: ['english', 'spanish'],
enableContextAware: true
});
const handleSubmit = async (e) => {
e.preventDefault();
setIsChecking(true);
try {
const checkResult = await checkTextAsync(comment);
if (checkResult.containsProfanity) {
// Show profanity warning
return;
}
// Submit clean comment
await submitComment(comment);
setComment('');
reset();
} catch (error) {
console.error('Error checking profanity:', error);
} finally {
setIsChecking(false);
}
};
return (
<form onSubmit={handleSubmit}>
<textarea
value={comment}
onChange={(e) => setComment(e.target.value)}
placeholder="Write your comment..."
rows={4}
/>
<button type="submit" disabled={isChecking || isDirty}>
{isChecking ? 'Checking...' : 'Post Comment'}
</button>
{result?.containsProfanity && (
<div className="bg-red-100 p-2 rounded mt-2">
<p>Please revise your comment:</p>
<ul>
{result.profaneWords.map(word => (
<li key={word}>⢠"{word}" ā Use alternative language</li>
))}
</ul>
</div>
)}
</form>
);
}Error Handling
Performance Optimization
Performance Tips:
- The hook automatically caches results to avoid redundant checks
- Use
isWordProfane()for lightweight single-word checks without state updates - Reset state with
reset()to free memory when form is cleared - Consider debouncing for real-time input validation
Hook Configuration
The hook accepts the same ProfanityCheckerConfig options as the core functions:
const { checkText } = useProfanityChecker({
languages: ['english', 'spanish'],
enableContextAware: true,
contextWindow: 5,
confidenceThreshold: 0.8,
severityLevels: true,
autoReplace: true,
fuzzyToleranceLevel: 0.7
});Cross-References
- Core Functions - Learn about
checkProfanity()andisWordProfane()functions - Filter Class - Object-oriented API for persistent configuration
- Quick Start - Basic React integration example
- Installation - React framework setup guide