Today, I learned about three important concepts in React: useState
, the spread operator (...
), and the onChange
event. To practice them, I created a small project that includes a Like, Dislike, and Comment feature. Here's how it works and what I learned.
What I Built
I created a simple React component where users can:
- 👍 Like
- 👎 Dislike
- 💬 Add comments
Each interaction updates the UI in real time using React Hooks!
What I Learned
1. useState
– React's Way to Handle State
React's useState
is a Hook that allows us to create state variables in functional components.
let [like, setLike] = useState(0);
let [dislike, setDislike] = useState(0);
let [comment, setComment] = useState("");
let [commentlist, setCommentList] = useState([]);
-
like
anddislike
store numbers. -
comment
stores a single input value. -
commentlist
is an array that stores all submitted comments.
2. onChange
– Tracking User Input
The onChange
event helps us track changes in form inputs. In my project, I used it to update the comment as the user types:
<textarea onChange={(event) => setComment(event.target.value)} />
Now the comment
state always holds the latest text from the user.
3. Spread Operator (...
) – Copy and Add to Arrays
To add a new comment without replacing the old ones, I used the spread operator. It lets us create a new array by copying all previous values and adding the new one:
setCommentList([...commentlist, comment]);
This line means:
"Create a new array with everything from
commentlist
, and then addcomment
at the end."
Full Code
import { useState } from "react";
function Hooks() {
let [like, setLike] = useState(0);
let [dislike, setDislike] = useState(0);
let [comment, setComment] = useState("");
let [commentlist, setCommentList] = useState([]);
return (
<div className="container">
<h1>Like: {like}</h1>
<h1>Dislike: {dislike}</h1>
<ul>
{commentlist.map((c, index) => (
<li key={index}>{c}</li>
))}
</ul>
<button onClick={() => setLike(like + 1)}>Like</button>
<button onClick={() => setDislike(dislike + 1)}>Dislike</button>
<br />
<textarea
placeholder="Comments Please..."
onChange={(event) => setComment(event.target.value)}
></textarea>
<button onClick={() => setCommentList([...commentlist, comment])}>
Add Comment
</button>
</div>
);
}
export default Hooks;
✅ Final Thoughts
This project helped me understand how React handles state and user interactions. Here's what I used:
- ✅
useState
for dynamic updates - ✅
onChange
to track input - ✅
...spread
to update arrays
This is a great starting point for more interactive apps. Next, I want to add features like deleting comments, editing them, or even saving them using localStorage
!
Top comments (0)