Lifecycle & Effects

Learn component lifecycle stages and how useEffect runs side effects in React.

Component Lifecycle and Effects (useEffect)

Every React component goes through different stages during its lifetime. A component is first created, then displayed on the screen, updated when its data changes, and finally removed when it is no longer needed. These stages are known as the component lifecycle.

In modern React, the useEffect Hook is used to perform actions during these lifecycle stages. It allows your application to run code after a component has been rendered, making it useful for tasks like loading data, updating the page title, setting timers, or listening for browser events.

Understanding the component lifecycle and the useEffect Hook is essential for building dynamic and efficient React applications.

What is the Component Lifecycle?

The component lifecycle describes the different stages a React component goes through from the moment it is created until it is removed.

The lifecycle has three main stages:

  • Mounting
  • Updating
  • Unmounting

Real-World Example

Imagine opening and closing a mobile application.

  • When you open the app, it starts and loads data.
  • While using it, the screen updates as you interact with it.
  • When you close the app, it stops running and frees up resources.

A React component behaves in a similar way.

Mounting

Mounting is the first stage of a component's lifecycle. It happens when the component is created and displayed on the screen for the first time.

Common tasks during mounting include:

  • Loading data from an API
  • Displaying initial content
  • Starting a timer
  • Setting the page title

This is one of the most common uses of the useEffect Hook.

Updating

A component enters the updating stage whenever its state or props change.

For example:

  • A user clicks a button.
  • A form value changes.
  • New data is received from a server.

React automatically re-renders the component to display the latest information.

Sometimes you may want to perform additional tasks whenever this update happens, such as saving data or displaying a notification. The useEffect Hook can handle these situations.

Unmounting

Unmounting happens when a component is removed from the screen.

Examples include:

  • Closing a popup window
  • Leaving a page
  • Removing a component from the interface

Before the component disappears, React gives you an opportunity to clean up resources. This process is called cleanup.

What is useEffect?

The useEffect Hook allows you to perform side effects after a component renders.

A side effect is any task that happens outside of simply displaying the user interface.

Examples include:

  • Fetching data from an API
  • Updating the browser title
  • Starting or stopping timers
  • Adding event listeners
  • Cleaning up resources

Basic useEffect Example

javascript
import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Component Loaded");
  }, []);

  return <h1>Welcome to React</h1>;
}

Explanation

  • useEffect() runs after the component is displayed.
  • The empty dependency array [] means the effect runs only once when the component mounts.

Running useEffect When Data Changes

Sometimes you want an effect to run only when a specific value changes.

javascript
import { useState, useEffect } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Count changed:", count);
  }, [count]);

  return (
    <button onClick={() => setCount(count + 1)}>
      {count}
    </button>
  );
}

How It Works

  • The component renders with an initial value of 0.
  • When the button is clicked, the state changes.
  • Because count is listed in the dependency array, useEffect runs again.

This is useful when you want to react to changes in specific data.

Cleaning Up Effects

Some effects need to be cleaned up when a component is removed. For example, timers should be stopped to prevent unnecessary background work.

javascript
import { useEffect } from "react";

function Timer() {
  useEffect(() => {
    const timer = setInterval(() => {
      console.log("Running...");
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return <h2>Timer Started</h2>;
}

Explanation

  • The timer starts when the component mounts.
  • The cleanup function stops the timer when the component unmounts.
  • This helps avoid memory leaks and improves performance.

Common Uses of useEffect

Developers commonly use useEffect for:

  • Fetching data from APIs
  • Updating the page title
  • Starting timers
  • Watching browser events
  • Saving data to local storage
  • Cleaning up timers or event listeners

These tasks are performed after React updates the user interface.

Real-World Example

Imagine you are building a weather application.

When the page opens:

  • useEffect sends a request to a weather API.
  • The API returns the latest weather information.
  • React updates the screen with the received data.

When the user leaves the page:

  • Any running timers or event listeners are removed.
  • Resources are cleaned up automatically.

This creates a fast and efficient user experience.

Best Practices

When using useEffect:

  • Keep effects focused on one task.
  • Use the dependency array correctly.
  • Clean up timers and event listeners when needed.
  • Avoid unnecessary effects that run on every render.
  • Write simple and readable effect functions.

These practices help improve performance and maintainability.

Summary

Every React component follows a lifecycle that includes mounting, updating, and unmounting. The useEffect Hook allows developers to perform tasks during these stages, such as loading data, updating the page title, or cleaning up timers and event listeners.

By understanding when and how useEffect runs, you can build React applications that are more efficient, responsive, and easier to maintain.

Key Takeaways

  • Every React component goes through mounting, updating, and unmounting stages.
  • The useEffect Hook performs actions after a component renders.
  • An empty dependency array [] runs the effect only once after mounting.
  • Adding values to the dependency array reruns the effect when those values change.
  • Cleanup functions stop timers, remove event listeners, and free resources.
  • useEffect is commonly used for API calls, timers, and browser interactions.
  • Keeping effects focused and cleaning up resources improves application performance.
  • Understanding the component lifecycle and useEffect is essential for building modern React applications.
Let's learn with DevBrainBox AI