React useEffect Hook

The useEffect hook is one of the most powerful hooks in React. It allows you to perform side effects in functional components, such as fetching data, subscribing to events, or directly interacting with the DOM. By using useEffect, you can mimic lifecycle methods from class components, such as componentDidMount, componentDidUpdate, and componentWillUnmount.


1 Basic Example: Logging to the Console using useEffect Hook

In this example, we use useEffect to log a message to the console whenever the component renders. This demonstrates how the hook works by default, running after every render.

</>
Copy
import React, { useEffect } from 'react';

function Logger() {
  useEffect(() => {
    console.log('Component has rendered.');
  });

  return <h2>Check the console for messages!</h2>;
}

export default Logger;

Explanation:

  • useEffect: Executes the provided function after every render of the component. Reference: React useEffect Hook
  • This example logs a message to the console to demonstrate how useEffect works by default.

Output: