chapter four
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 clean-up 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’s really good at efficiently deciding what should update and scheduling any changes. Sometimes, however, we need our components to reach outside of 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:
- Setting the page title imperatively
- Working with timers like setInterval or setTimeout
- Measuring the width or 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