Fetching Data using Lifecycle Methods

In this example, UserDataFetcher is a class component that makes use of the componentDidMount lifecycle method to perform a fetch request to an API for user data when the component is first mounted to the DOM. The componentWillUnmount lifecycle method is also defined to demonstrate where you might include cleanup logic, such as cancelling fetch requests to prevent memory leaks in more complex applications.

JavaScript
import React, { Component } from "react";

class UserDataFetcher extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userData: null,
            isLoading: true,
            error: null,
        };
    }

    componentDidMount() {
        fetch("https://jsonplaceholder.typicode.com/users/1")
            .then((response) => {
                if (!response.ok) {
                    throw new Error("Network response was not ok");
                }
                return response.json();
            })
            .then((data) => this.setState({ userData: data,
                                            isLoading: false }))
            .catch((error) => this.setState({error,isLoading: false }));
    }

    componentWillUnmount() {
        // Perform any necessary cleanup here, 
        // such as aborting fetch requests
        // or unsubscribing from external data sources.
        console.log(`Component is being unmounted and
                     cleanup is in progress.`);
    }

    render() {
        const { userData, isLoading, error } = this.state;

        if (isLoading) {
            return <div>Loading...</div>;
        }

        if (error) {
            return <div>Error: {error.message}</div>;
        }

        return (
            <div>
                <h1>User Data</h1>
                <p>Name: {userData.name}</p>
                <p>Email: {userData.email}</p>
                {/* Render more user details as needed */}
            </div>
        );
    }
}

export default UserDataFetcher;

Output:

Are Class Components still useful in React ?

With the rise of functional components and hooks in React, class components have taken a backseat in modern React development. However, there are still scenarios where class components offer advantages over functional components.

In this article, we’ll explore the continued relevance of class components in React and discuss situations where they might still be preferred.

Table of Content

  • Scenarios to use Class Components
  • Fetching Data using Lifecycle Methods
  • Conclusion

Similar Reads

Scenarios to use Class Components:

1. Complex State Management:...

Fetching Data using Lifecycle Methods

In this example, UserDataFetcher is a class component that makes use of the componentDidMount lifecycle method to perform a fetch request to an API for user data when the component is first mounted to the DOM. The componentWillUnmount lifecycle method is also defined to demonstrate where you might include cleanup logic, such as cancelling fetch requests to prevent memory leaks in more complex applications....

Conclusion

While functional components and hooks have become the preferred choice for most React development due to their simplicity and flexibility, class components still have their place in certain scenarios. Whether it’s managing complex state, leveraging lifecycle methods, ensuring compatibility with existing codebases, integrating with third-party libraries, or catering to personal preferences, class components continue to offer value in the React ecosystem....