Hey everyone! 👋 Welcome to my 5th blog post in this series on learning React with TypeScript. If you've been following along, we’ve already covered how to:
In this post, we’ll take a step further and learn how to pass event handlers and work with `useState` using a real-world example.
💡 Instead of the usual `setCount` examples you’ll see all over the internet, we’re building something practical for actual projects: a User List component.
`useState` is a React Hook that allows you to manage state in functional components. It's one of the most commonly used hooks in React, introduced in version 16.8.
Why use `useState`?
It gives you the ability to store and update component-level data like form inputs, toggle states, user lists, and more — without needing class components.
Example:
const [value, setValue] = useState(initialValue);
- A UserList component under the User folder
- Use useState to store a list of users
- On button click, we’ll add a dummy user
- Display the user list in a clean HTML table
1. Import Hook
import { FC, useState } from "react";
2. Define the User Type
export type User = {
id: number,
name: string,
emailAddress: string,
moobileNumber: string
};
3. Create Component and State
const UserList: FC = () => {
const [users, setUsers] = useState<User[]>([]);
4. Add Dummy User Function
const addUser = () => {
const newUser: User = {
id: users.length + 1,
name: `User ${users.length + 1}`,
emailAddress: `user${users.length + 1}@theravinder.com`,
moobileNumber: `+44-779945881${users.length}`
};
setUsers([...users, newUser]);
}
5. Render UI with Button and Table
return (
<>
<div><h1>User List</h1></div>
<div><button onClick={addUser}>Add</button></div>
{users.length > 0 ? (
<table>...</table>
) : (
<p>No users added yet.</p>
)}
</>
);
- You learned how to use useState in a practical way
- Passed an event handler to a button
- Managed and displayed a list dynamically using JSX
- Rendered everything inside a simple HTML table
In the next blog, we’ll explore how to delete users and talk about the importance of using the key prop when rendering lists.
Download full working code from GitHub https://github.com/ravinder25886/basic-component/tree/feature/useState-event-handling
Thanks, for reading the blog, I hope it helps you. Please share this link on your social media accounts so that others can read our valuable content. Share your queries with our expert team and get Free Expert Advice for Your Business today.
Hire me on Linkedin
My portfolio