Chapter 5. React component lifecycle events

 

This chapter covers

  • Getting a bird’s-eye view of React component lifecycle events
  • Understanding event categories
  • Defining an event
  • Mounting, updating, and unmounting events

Chapter 2 provided information about how to create components, but there are certain situations in which you need more granular control over a component. For instance, you may be building a custom radio button component that can change in size depending on the screen width. Or perhaps you’re building a menu that needs to get information from the server by sending an XHR request.

One approach would be to implement the necessary logic before instantiating a component and then re-create it by providing different properties. Unfortunately, this won’t create a self-contained component, and thus you’ll lose React’s benefit of providing a component-based architecture.

The best approach is to use component lifecycle events. By mounting events, you can inject the necessary logic into components. Moreover, you can use other events to make components smarter by providing specific logic about whether or not to rerender their views (overwriting React’s default algorithm).

Going back to the examples of a custom radio button and menu, the button can attach event listeners to window (onResize) when the button component is created, and detach them when the component is removed. And the menu can fetch data from the server when the React element is mounted (inserted) into the real DOM.

5.1. A bird’s-eye view of React component lifecycle events

5.2. Categories of events

5.3. Implementing an event

5.4. Executing all events together

5.5. Mounting events

5.6. Updating events

5.7. Unmounting event

5.8. A simple example

5.9. Quiz

5.10. Summary

5.11. Quiz answers

sitemap