4 Working with side effects

 

This chapter covers

  • Recognizing types of side effects in components
  • Wrapping side effects with the useEffect hook
  • Controlling when an effect runs by specifying a dependency list
  • Returning a cleanup function from an effect
  • Using an effect to fetch data for a component

React transforms our data into UI. Each component plays its part, returning its contribution to the overall user interface. React builds the tree of elements, compares it with what’s already rendered, and commits any necessary changes to the DOM. When the state changes, React goes through the process again to update the UI. React is really good at efficiently deciding what should update and scheduling any changes.

Sometimes, however, we need our components to reach outside this data-flow process and directly interact with other APIs. An action that impinges on the outside world in some way is called a side effect. Common side effects include the following:

  • Setting the page title imperatively
  • Working with timers like setInterval or setTimeout
  • Measuring the width, height, or position of elements in the DOM
  • Logging messages to the console or other service
  • Setting or getting values in local storage
  • Fetching data or subscribing and unsubscribing to services

4.1 Exploring the useEffect API with simple examples

 

4.1.1 Running side effects after every render

 
 

4.1.2 Running an effect only when a component mounts

 
 

4.1.3 Cleaning up side effects by returning a function

 
 
 
 

4.1.4 Controlling when an effect runs by specifying dependencies

 
 
 

4.1.5 Summarizing the ways to call the useEffect hook

 
 
 

4.1.6 Calling useLayoutEffect to run an effect before the browser repaints

 
 

4.2 Fetching data

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest