useEffect and component lifecycle
Components in React have a 'lifecycle' that describes three phases:
- Mounting
- The creation and insertion of the component into the DOM.
- Updating
- Update to the component caused by changes to its props or state.
- Unmounting
- The removal of the component from the DOM.
React hooks, such as useEffect
give us a way to leverage the lifecycle of a component, performing specific actions depending on the current phase of the lifecycle.
For example, the function body of the first argument to the useEffect
below will execute when the component is first mounted, but not when there are updates to state (that trigger re-renders of the component). This is due to the second useEffect
argument (the empty dependency array).
React.useEffect(() => {
// implementation details omitted
}, [])
useEffect
is often used to opt into the lifecycle of your components to introduce side-effects, such as fetching asynchronous data. The interaction between side-effects and component lifecycle can be a useful way to control the execution of expensive operations that don't need to be executed on every render.