Component Lifecycle
intermediatePart of State & Props
Theory
Every React component goes through a lifecycle: it is created (mount), updated (re-render), and removed (unmount). In functional components, the useEffect hook handles all lifecycle phases.
Lifecycle Phases
- Mounting — component is added to the DOM. Run initial data fetching, set up subscriptions.
- Updating — component re-renders due to state or prop changes. React to changes.
- Unmounting — component is removed from the DOM. Clean up subscriptions, timers, event listeners.
useEffect
useEffect runs side effects after render. Its dependency array controls when it runs:
useEffect(() => {
// Runs after every render
})
useEffect(() => {
// Runs only on mount
}, [])
useEffect(() => {
// Runs when count changes
}, [count])Cleanup Function
Return a function from useEffect to clean up — this runs on unmount and before re-running the effect. Use it for clearing timers, aborting fetch requests, and unsubscribing from events.
useLayoutEffect
useLayoutEffect runs synchronously after DOM mutations but before the browser paints. Use it for DOM measurements and animations that need to happen before the user sees the result.
Practical Examples
Exercises
Window Resize Logger
Create a component called WindowSize that logs the current window width and height whenever the window is resized. Use useEffect to add and clean up the resize event listener. Display the dimensions on screen.
Expected Output:
Displays width x height that updates on window resize