How to display remaining characters in a textarea using useRef in React?
Track and display the number of remaining characters in a textarea using useRef and useState hooks.
intermediateForms and inputsreactuseRefformscharacter counter
Published: 10/26/2025
Updated: 10/26/2025
Question
How to display remaining characters in a textarea using React useRef?
Answer
You can use useState to track characters and useRef to access the input field directly.
import { useState, useRef } from 'react';
function TextAreaCounter() {
const maxLength = 100;
const [remaining, setRemaining] = useState(maxLength);
const textRef = useRef();
const handleChange = () => {
const currentLength = textRef.current.value.length;
setRemaining(maxLength - currentLength);
};
return (
<div>
<textarea ref={textRef} onChange={handleChange} maxLength={maxLength} />
<p>{remaining} characters remaining</p>
</div>
);
}
- ✅
useRefgives you direct access to the DOM node for quick reads. - ✅
useStateupdates only the displayed value.
Real-World Example
- Textarea limits in comment boxes
- Tweet-style input character indicators
- Form validations
Quick Practice
Create a textarea that turns the counter text red when the user reaches 90% of the limit.
Summary
Combine useRef for DOM access with useState for UI reactivity to build smooth input counters.
Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions
Why useRef instead of just state?
Refs are useful for direct DOM access, especially when not tied to rendering logic.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.