Improving your mental model of useEffect
--
Hooks landed in React a few months ago, and there has been a lot of excitement around them in terms of figuring out how to best use them, best practices, and how they map to current concepts in React and the lifecycle.
Many React developers are familiar with the React Component lifeCycle, and hooks like:
When trying to understand the useEffect hook, it’s natural to want to map it to the lifecycle methods we already know. At first glance, useEffect seems to be like a combination of componentDidMount and componentDidUpdate.
While this can be a useful way of looking at it at first, it may not be the most accurate.
Instead of thinking in terms of ‘what do I want to do when I mount, or when I update’, it's more useful to ask:
What values does this effect depend on?
To better understand where the idea of useEffect = componentDidMount + componentDidUpdate comes from, we will first look at a typical class-based component that is doing some data fetching.
When the component first mounts, we fetch data for the id that has been passed down as a prop. When the component updates, since many things other than just the id prop changing can cause this method to run, we want to ensure that id has actually changed — or some poor server is going to get a DDoS attack with a bunch of API calls that we don’t need.
While the lifecycle hooks of componentDidMount and componentDidUpdate with class-based components are common places to make a request based on a property, the fact that the component is mounting or updating is not really the thing we are concerned with.
What we are concerned with: “what data does the query depend on?”