Day 3: State & Interactive Components
Day 3: State & Interactivity
Static components are boring. Today, we learn how to make our app interactiveâreacting to clicks, inputs, and changes. The secret sauce is State.
Events
Handling events in React is similar to HTML, but with camelCase syntax.
function Button() {
function handleClick() {
alert('Button clicked!');
}
// Note: onClick, not onclick
// Pass the function, don't call it (no parentheses)
return <button onClick={handleClick}>Click Me</button>;
}
What is State?
State is data that changes over time inside a component. When state changes, React automatically re-renders the component to reflect the new data.
To use state, we use a Hook called useState.
The useState Hook
Hooks are special functions that let you âhook intoâ React features. useState is the most common one.
import { useState } from 'react';
function Counter() {
// 1. Declare a state variable called "count" initialized to 0.
// 2. React gives us a function "setCount" to update it.
const [count, setCount] = useState(0);
function increment() {
// 3. Update state. This triggers a re-render.
setCount(count + 1);
}
return (
<div>
<p>Current Count: {count}</p>
<button onClick={increment}>Add 1</button>
</div>
);
}
Breaking It Down
const [count, setCount] = useState(0);
count: The current value of the state.setCount: The function to update the state.0: The initial value.
Important Rule: Never Modify State Directly
Wrong: count = count + 1;
Right: setCount(count + 1);
If you modify the variable directly, React wonât know it changed, and the UI wonât update.
Arrays and Objects in State
When dealing with objects or arrays, you must create a new object/array copy. You cannot mutate the existing one.
const [user, setUser] = useState({ name: 'Jack', age: 25 });
// â Wrong: mutating the object
// user.age = 26;
// â
Right: creating a new object with spread operator
setUser({ ...user, age: 26 });
Same for arrays:
const [todos, setTodos] = useState(['Learn React']);
// â
Right: create new array
setTodos([...todos, 'Build a Project']);
Controlled Inputs
How do we handle form inputs? We sync the input value with React state. This is called a Controlled Component.
function TextInput() {
const [text, setText] = useState('');
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<p>You typed: {text}</p>
</div>
);
}
Now, text state is the âsingle source of truthâ for that input.
Homework for Day 3:
- Create a âLight Switchâ component.
- It should have a button âToggle Lightâ.
- When clicked, the background color of the div changes from white (on) to black (off), and the text changes from âLight is ONâ to âLight is OFFâ.
Get ready for Day 4, where things get asynchronous with useEffect!