Bringing Apps to Life: Interactivity and State in React
While props allow us to pass data into components, State is what allows our applications to actually "remember" things and change over time. In this guide, we will explore how to handle user interactions and manage dynamic data using React Hooks.
1. Listening to User Events
In standard HTML, you might use lowercase attributes like onclick. In React, events are named using camelCase (e.g., onClick, onChange, onSubmit). To make a component interactive, we attach these events directly to our elements.
Let's imagine we are building a simple RSVP Tracker for an event:
function EventPage() {
return (
<div>
<h1>Tech Conference 2026</h1>
<button onClick={ () => console.log('Button clicked!') }>
Confirm Attendance
</button>
</div>
);
}
2. Creating Event Handlers
While you can write logic inline, it’s cleaner to define a separate function to "handle" the event. This function lives inside your component, before the return statement.
function EventPage() {
function handleRSVP() {
alert("Thank you for registering!");
}
return (
<div>
<h1>Tech Conference 2026</h1>
<button onClick={handleRSVP}>Confirm Attendance</button>
</div>
);
}
3. Managing Data with the useState Hook
To keep track of a value that changes—like the number of people who have RSVP'd—we use a Hook called useState. Hooks are special functions that let you "hook into" React features.
When you call React.useState(), it returns an array with two items:
- The State Variable: The current value (e.g.,
guestCount). - The Setter Function: A function used to update that value (e.g.,
setGuestCount).
Implementation Example:
function EventPage() {
// Initialize state at 0
const [guestCount, setGuestCount] = React.useState(0);
function handleRSVP() {
// Update the state based on the previous value
setGuestCount(guestCount + 1);
}
return (
<div>
<h1>Tech Conference 2026</h1>
<p>Current Attendees: {guestCount}</p>
<button onClick={handleRSVP}>RSVP Now</button>
</div>
);
}
4. State vs. Props: The Key Difference
It is important to distinguish between these two ways of handling data:
| Feature | Props | State |
|---|---|---|
| Origin | Passed from Parent to Child. | Created inside the Component. |
| Mutability | Read-Only (Immutable). | Can be changed via Setter function. |
| Purpose | Configuring the component. | Tracking interactive data. |
Whenever the State changes, React automatically re-renders the component to update the UI. This ensures that your screen always matches your data without you having to manually manipulate the DOM.
Pro Tip: You can pass a piece of State down to a child component as a Prop. However, the logic to change that state should stay where the state was born!
