6 Effects and the React component life cycle

 

This chapter covers

  • Running effects inside components
  • A complete guide to the React component life cycle
  • Mounting, unmounting, and rendering components
  • Introducing life cycle methods for class-based components

React components use JavaScript XML (JSX) to send information to the user in the form of HTML. But components need to do a lot more than that to be useful in an application. In React, everything that happens, happens in some component, so if your application wants to set a cookie, load some data, handle form input, display the user’s camera, start or stop a timer, or a myriad of other dynamic capabilities, you need more than just JSX.

If you want your component to load some data from a server, you want the effect to run as soon as the component loads, but then you don’t need the effect to run again even if your component re-renders. On the other hand, if you want to set a cookie with the last username entered into the login field, you want that effect to run every time the user types in the input field. If you want to display a timer inside your component, you want the timer to start ticking as your component loads, but you also want the timer to stop ticking as your component later unloads, to avoid unnecessarily clogging up resources.

6.1 Running effects in components

6.1.1 Running an effect on mount

6.1.2 Running an effect on mount and cleanup on unmount

6.1.3 Running cleanup on unmount

6.1.4 Running an effect on some renders

6.1.5 Running an effect and cleanup on some renders

6.1.6 Running an effect synchronously

6.2 Understanding rendering

6.2.1 Rendering on mount

6.2.2 Rendering on parent render

6.2.3 Rendering on state update

6.2.4 Rendering inside functions

6.3 The life cycle of a class-based component

6.3.1 Life cycle methods