Skip to main content

useMentions

Overview

The useMentions hook provides comprehensive mention functionality for text inputs. It automatically detects @mentions in text, fetches user suggestions, manages mention state, and handles mention selection. This hook is designed to work with text input components that need full mention support.

Usage Example

Parameters & Returns

Required Props

The hook requires the following props to function:

Return Values

The hook returns an object with the following properties:

Type Definitions

Behavior & Features

Automatic Mention Detection

  • Detects when user types @ followed by 3+ characters
  • Only activates when there’s no active text selection
  • Uses regex pattern /^@[\w.]+$/ to validate mention triggers
  • Supports usernames with letters, numbers, underscores, and dots
  • Implements 1-second debounce to avoid excessive API calls
  • Automatically fetches user suggestions based on typed query
  • Clears suggestions when mention pattern no longer matches

State Management

  • Tracks all mentions added to the text
  • Prevents duplicate mentions for the same user
  • Maintains mention list independent of text content
  • Provides functions to manually manage mention state

Text Replacement

  • Automatically replaces mention trigger with selected username
  • Maintains proper spacing after mention insertion
  • Focuses back to input after mention selection

Integration Requirements

To use this hook effectively, your text input component must:
  1. Track cursor position: Update cursorPosition on text changes and cursor movements
  2. Track selection state: Monitor whether text is selected vs just cursor positioned
  3. Provide focus function: Allow the hook to refocus the input after mention selection
  4. Handle content updates: Use the provided setContent function for text updates

Advanced Usage

Custom Mention Validation

Manual Mention Management