Get the Number of Characters for a Text Area Using React's useState Hook

Share this video with your friends

Send Tweet

We use the useState hook to keep track of the total number of characters in the text area. We create a variable called characterCount which will hold our state, a function that will update it called setCharacterCount and we set the initial value of our characterCount to 0 (passing 0 to useState).

We then set up an onChange event handler on the text area, so that every time we type, we update our character count by calling the setCharacterCount function

Finally, we get the total number of characters in the text area by using e.target.value.length. Then we pass it to the setChracterCount function to update our character count.

~ 4 years ago

Can we use useState() with strings or objects ?

Mahmoud Abdelwahabinstructor
~ 4 years ago

Yes you can! Not just numbers

~ 2 years ago

And can we create some kind of text as initial and check if the text we type in the form is equivalent to the initial one?