Lesson 4 of 15
Giving Your App a Brain (State & Events)
Lesson Updated: Apr 28, 2026
Requirement
Understand that static components are boring. To make an app interactive (like opening a menu or typing in a form), a component needs a memory to track its current status. In React, this memory is called "State", and we change that memory by listening to user "Events" like clicks or keystrokes.
Assignments (Start First)
- Simple beginner UI task: Build a
Countercomponent. It should display a number starting at 0, and have a button labeled "Add 1". Every time the user clicks the button, the number should increase by 1. - Slightly improved version: Upgrade your
Counter. Add a "Decrease" button and a "Reset" button. Implement logic so the counter can never go below zero. - Practical real-world component: Create a
LikeButtoncomponent for a social media post. It should display a heart icon and the text "Like". When clicked, the state should toggle: the heart becomes filled, the text changes to "Liked!", and a small number next to it increments by 1. Clicking it again undoes the action. - "The Escalation": Build a
ThemeTogglecard. Create a card component containing some text and a toggle switch. Use state to track whether it is in "light mode" or "dark mode". When toggled, use inline styling or class names to change the background color and text color of the entire card dynamically.
Lessons (Optional)
- State (useState): A React hook that lets functional components hold onto data between renders. It gives you a variable to read, and a function to update it.
- Events: React handles events similarly to HTML, but using camelCase (e.g.,
onClick,onChange). - Immutability: Never modify a state variable directly. Always use the provided setter function.
- Interactivity: When an event fires, it calls your state setter. This is the core cycle of React interactivity.
The Summary and Quizzes
- Concept explanation: State is the current snapshot of your component's memory. Events are the triggers the user fires to change that memory.
- Why it works in React: React constantly watches your State variables. The moment you update a state variable via an event, React automatically re-renders only that specific component to display the newest data.
- Challenge question: If you have
const [isOpen, setIsOpen] = useState(false), what exact code would you put inside anonClickevent to toggleisOpento the opposite of its current value?