Managing State and Events
Introduction: Making Your App Interactive
Welcome back! In the last lesson, you learned how to build reusable components and pass data to them using props. Now, you are ready to make your React app interactive. In this lesson, you will learn how to let users add new books to a reading list and see the list update right away. This is possible thanks to two important ideas in React: state and event handling.
State lets your app remember things, like which books are in your list or what the user has typed into a form. Event handling lets your app respond to user actions, such as clicking a button or submitting a form. By the end of this lesson, you will know how to use both to build a simple, interactive reading list.
Using State with useState
In React, the key to making apps interactive is state. State represents values that change over time and that React needs to keep track of in order to re-render the UI correctly. Without state, your components would only be able to display static content.
Why not just use let?
You might wonder: why not write something like this?
The problem is that React won’t know this value has changed. React’s rendering system is built around the idea that when state updates, the component should re-render to reflect the change. If you use a plain variable, React has no way of detecting that change, so the UI will stay the same on screen.
Introducing useState
React solves this with the useState hook:
Hook: A hook is a special React function that lets you “hook into” internal features like state and lifecycle. All hooks start with use, e.g. useState, useEffect.
-
useState:This hook gives you two things:- A state variable (like
books,newTitle,newAuthor). - A setter function (like
setBooks,setNewTitle,setNewAuthor) that updates the state.
- A state variable (like
-
Initial State: The value you pass into
useState(...)is the initial state. For example:useState<Book[]>(initialBooks)means the list of books starts with two predefined items.useState("")means bothnewTitleandnewAuthorstart as empty strings.
