Problem:
-- Input field: updates on every keystroke.
-- Show a live count of each character used (e.g., typing “hello”
→ {h:1, e:1, l:2, o:1}).
-- Implement using React functional components, useState, and useEffect.
-- Optimize for performance using useMemo or throttling if input is very large.
Solution:
Here’s a simple and clean example of a real-time character frequency counter using React 👇
🧾 CharacterCounter.jsx
import { useState } from "react";
export default function CharacterCounter() {
const [text, setText] = useState("");
const [frequency, setFrequency] = useState({});
const handleChange = (e) => {
const input = e.target.value;
setText(input);
const freq = {};
for (let char of input) {
freq[char] = (freq[char] || 0) + 1;
}
setFrequency(freq);
};
return (
<div style={{ padding: "20px", maxWidth: "400px", margin: "auto" }}>
<h2>Real-time Character Frequency Counter</h2>
<textarea
value={text}
onChange={handleChange}
placeholder="Type something..."
rows="5"
style={{ width: "100%", marginBottom: "15px" }}
/>
<h4>Character Frequencies:</h4>
<ul>
{Object.entries(frequency).map(([char, count]) => (
<li key={char}>
{char === " " ? "(space)" : char} : {count}
</li>
))}
</ul>
</div>
);
}
🧠 How it works:
textstores what the user types.- Every time the input changes,
handleChangeupdates the frequency object. - The frequency of each character is calculated and displayed in real-time.
- Spaces are handled nicely (displayed as
(space)).
✅ This component is fully interactive and updates instantly as the user types.