Browse Courses

Function Comp Lifecycle

This document explains the four phases of the React function component lifecycle—mounting, updating, unmounting, and error handling—using hooks and practical examples.

This document covers the four phases of the React function component lifecycle—mounting, updating, unmounting, and error handling—explaining how hooks like useState and useEffect enable similar control as class lifecycle methods.


Function Component Lifecycle in React

React function components are the core building blocks for user interfaces. Understanding their lifecycle is essential for managing state, side effects, and cleanup throughout a component’s existence.

Lifecycle Phases Overview

React function components experience four main phases:

  • Mounting
  • Updating
  • Unmounting
  • Error Handling

Mounting Phase

During mounting, React initializes the component and prepares it for rendering. Key steps include:

  • Initialization: React runs the function body, setting up the initial structure.
  • State Initialization: useState is used to declare and initialize state variables.
  • Side Effects: useEffect with an empty dependency array runs side effects once after the initial render.

Example: State Initialization

1import React, { useState } from 'react'
2
3function Counter() {
4  const [count, setCount] = useState(0)
5  return <div>Count: {count}</div>
6}

Example: Side Effect on Mount

 1import React, { useState, useEffect } from 'react'
 2
 3function DataFetcher() {
 4  const [data, setData] = useState(null)
 5  useEffect(() => {
 6    fetch('https://api.example.com/data')
 7      .then(res => res.json())
 8      .then(setData)
 9  }, [])
10  return <div>Data: {JSON.stringify(data)}</div>
11}

Updating Phase

In the updating phase, React responds to changes in state or props by re-invoking the function body and re-evaluating the JSX.

Example: Updating State

 1import React, { useState } from 'react'
 2
 3function MyComponent() {
 4  const [count, setCount] = useState(0)
 5  function increment() {
 6    setCount(prev => prev + 1)
 7  }
 8  return (
 9    <div>
10      <p>Count: {count}</p>
11      <button onClick={increment}>Increment</button>
12    </div>
13  )
14}

Unmounting Phase

When a component is removed from the DOM, React performs cleanup operations. This is handled by returning a cleanup function from useEffect.

Example: Cleanup on Unmount

 1import React, { useEffect } from 'react'
 2
 3function Timer() {
 4  useEffect(() => {
 5    const interval = setInterval(() => {
 6      console.log('interval tick')
 7    }, 1000)
 8    return () => clearInterval(interval)
 9  }, [])
10  return <div>Timer running...</div>
11}

Error Handling Phase

If an error occurs during rendering or in a child component, React routes it to the nearest error boundary. Error boundaries are special components that catch errors and display fallback UIs, preventing the entire app from crashing.


Conclusion

React function component lifecycle includes mounting, updating, unmounting, and error handling. Hooks like useState and useEffect provide control over state, side effects, and cleanup, while error boundaries ensure robust error handling.


FAQ

  1. The sequence of phases a component goes through: mounting, updating, unmounting, and error handling.
  2. The process of rendering static content only.
  3. The way React handles CSS styling.
  4. The order in which props are passed.
(1) The lifecycle includes mounting, updating, unmounting, and error handling.

Resources such as timers or subscriptions may not be released, potentially causing memory leaks or unwanted side effects.

  1. State is initialized using useState
  2. Side effects can be set up with useEffect
  3. The function body is executed to set up the component
  4. Error boundaries are set up inside useEffect
(4) Error boundaries are not set up inside useEffect; they are special components.

React routes the error to the nearest error boundary, which displays a fallback UI and prevents the app from crashing.

PhaseDescription
A. Mounting1. Handles cleanup when component is removed
B. Updating2. Initializes component and state, runs effects
C. Unmounting3. Responds to state or prop changes
D. Error Handling4. Catches errors and displays fallback UI
A-2, B-3, C-1, D-4.

Ensure that the cleanup function in useEffect properly clears the timer during the unmounting phase.

useEffect with an empty dependency array runs only once after the initial render, similar to componentDidMount in class components.

True. This pattern is used for side effects that should run only on mount.

  1. Mounting
  2. Updating
  3. Styling
  4. Unmounting
(3) Styling is not a lifecycle phase.

Error boundaries catch errors in their child components and display a fallback UI, preventing the entire app from crashing.

Hooks like useState and useEffect allow function components to manage state, side effects, and cleanup, providing similar control as class lifecycle methods.