Lifecycle Phases
A component’s lifecycle can be divided into three main phases:- Mounting: Component is created and inserted into the DOM
- Updating: Component re-renders due to changes in props or state
- Unmounting: Component is removed from the DOM
Lifecycle in Function Components
Function components use Hooks to handle lifecycle events. The primary Hook for lifecycle management isuseEffect.
Mounting and Updating
Effect Dependencies
The dependency array controls when the effect runs:Cleanup (Unmounting)
Return a cleanup function fromuseEffect to run code when the component unmounts or before the effect runs again:
useLayoutEffect
useLayoutEffect is similar to useEffect but fires synchronously after all DOM mutations, before the browser paints:
When to use useLayoutEffect: Use it when you need to read layout information (like scroll position or element size) and synchronously make changes before the browser paints. For most cases,
useEffect is preferred.useInsertionEffect
useInsertionEffect fires before all DOM mutations. It’s primarily used by CSS-in-JS libraries to inject styles:
Lifecycle in Class Components
Class components have explicit lifecycle methods. While function components with Hooks are now preferred, understanding class lifecycle methods is useful for maintaining existing code.Mounting
Called when a component is created and inserted into the DOM:Updating
Called when props or state change:According to the React source code in
ReactBaseClasses.js, forceUpdate() will not invoke shouldComponentUpdate, but it will invoke componentWillUpdate and componentDidUpdate.Unmounting
Called when a component is removed from the DOM:Error Boundaries
Class components can catch errors in child components using error boundaries:Function vs Class Lifecycle Comparison
- Function Component
- Class Component
Common Lifecycle Patterns
Fetching Data
Subscribing to External Data
Derived State
Next Steps
Hooks Overview
Explore all available React Hooks
Rendering
Learn how React renders and updates the DOM