Component Lifecycle Methods (or Hooks)

  • Excercice: Create a component that fetches data from an API and displays it use useEffectto handle and clean up if necessary.
  • Practice: Understand how to use useEffectfor different scenarios, like fetching data, setting up subscriptions and cleaning up resourses

Step 1: Set Up the Component

Start by creating a basic functional component in React.

const DataFetchingComponent = () => {
    return(
        <div>
            <h1>Data Fetching Component</h1>
        </div>
    );
};

export default DataFetchingComponent;

Step 2: Add state for storing data

You need a state variable to store the data fetched from the API. Use the useState hook for this.

import {useState} from 'react';

const DataFetchingComponent = () => {
    const [data, setData] = useState(null); //Initialize state for storing data
    
    return(
        <div>
            <h1>Data Fetching Component</h1>
        </div>
    );
};

export default DataFetchingComponent;
  • Explanation
    • useState(null)initializes data with value of null.
    • setData is the function you will use to update the data state

Step 3: Fetch data with useEffect

Next use the useEffect hook to fetch data when component mounts.

import {useState, useEffect} from 'react';

const DataFetchingComponent = () => {
    const [data, setData] = useState(null);
    
    useEffect(() => {
        const fetchData = async() =>{
            try{
                const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                const result = await response.json();
                setData(result);
            } catch(error) {
                console.error(`Error fetching data: ${error}`);
            }
        };
        
        fetchData();
    },[]); // Empty dependency array to run only once on mount
    
    return(
        <div>
            <h1>Data Fetching Component</h1>
        </div>
    )
};

export default DataFetchingComponent;
  • Explanation
    • useEffect(() => {}, []) runs the code once, when the component mounts. The empty array [] ensures this.
    • fetchData is an asynchromous function that fetches data from the given API.
    • setData(result) updates the data state with the fetched result.

Step 4: Render the fetched data

Now that the data is fetched and stored in state, render it in your component.

import {useState, useEffect} from 'react';

const DataFetchingComponent = () => {
    const [data, setData], useState(null);
    
    useEffect(() => {
        const fetchData = async() => {
            try{
                const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                const result = await response.json();
                setData(result);
            }catch(error){
                console.error(`Error fetching data: ${error}`);
            }
        }
        
        fetchData();
    }, []);
    
    return(
    <div>
        <h1>Fetching data example</h1>
        {data ? (
            <ul>
            {data.map((item, idx) => (
                <li key={idx}>{item.title}</li>
            ))}    
            </ul>
            ) : (
                <p>Loading...</p>
            )
        }
    </div>
    );
};

export default DataFetchingComponent;
  • Explanation
    • data ? (...):(...): This is a conditional (ternary) operator. If data is not null, it renders a list of data; otherwise, it shows a “Loading…” message.
    • data.map((item, idx) => ...): Iterates over the fetched data array and renders each item as a list element.

Handle Cleanup (if necessary)

In some cases, you might to clean up after side affects. For example, if you set up subscriptions or timers. In this case, no clean up in required because there’s no ongoing subscription or timer.

import {useState, useEffect} from 'react';

const DataFetchingComponent = () => {
    const [data, setData], useState(null);
    
    useEffect(() => {
        const fetchData = async() => {
            try{
                const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                const result = await response.json();
                setData(result);
            }catch(error){
                console.error(`Error fetching data: ${error}`);
            }
        }
        
        fetchData();
        
        //Cleanup function (not necessary here)
        return () =>{
            //cleanup logic (e.g., unsubscribe, clear timers, etc.)
        }
    }, []);
    
    return(
    <div>
        <h1>Fetching data example</h1>
        {data ? (
            <ul>
            {data.map((item, idx) => (
                <li key={idx}>{item.title}</li>
            ))}    
            </ul>
            ) : (
                <p>Loading...</p>
            )
        }
    </div>
    );
};

export default DataFetchingComponent;

Key Takeaways

  • useEffect: This hook is essential for side effects in functional components, such as data fetching. It can run on mount, on updates, or on unmount depending on the dependency array.
  • useState: Manages the local state of the component, allowing it to be reactive to changes (e.g., updating the UI when new data is fetched).
  • Conditional Rendering: Handle different states (loading, error, success) gracefully with conditional logic.

You can find this example using TypeScrip on my github

Share this post:  

FacebookTwitterLinkedInWhatsApp