Interactivity, State, and Hooks

Let's add interactivity to the page in this lesson!

Using React state

At this point, React has taken over part of our page and is drawing the seats, which is nice, but we still need to add some reactive elements. We need increased interactivity.

In React, we can use JSX to specify event handlers on React elements in much the same way we would when writing old-school JavaScript embedded in HTML. The problem is how to make changes to our components as a result of those events. As mentioned, the props we pass into each component are immutable, which means that if we want to change something about a component, we can’t use props. As we discussed earlier, React uses the term state to refer to the parts of a component that change and which parts that trigger an update to how the component is displayed when they are changed.

To be clear, although a component can’t change its own props, changing the state of a component can cause that component to rerender child components with new props.

Because state changes are used by React to trigger a redraw of the page, React requires us to register them with the system. We can’t simply change the value of a variable and be done with it. React allows us to designate a value as being part of the state and gives us a special setter for that value using a mechanism called hooks.

React hooks

Hooks are new in React as of version 16.8. Before then, components defined as functions could not manage changing state (components defined as classes could manage state using a different mechanism).

As mentioned earlier, the React core team has said that hooks and functional components are the way of the future, which is why we will be focusing on using hooks to manage state in this book.

Here’s the code for the Seat component that changes status when clicked:

Get hands-on with 1200+ tech skills courses.