All articles
react

Demo of componentDidMount using useEffect, using API

Share this article

Share on LinkedIn Share on X (formerly Twitter)

Component description

This component renders a random image whenever its mounted, which is obtained from a third party API.

You need to refresh the page to see a new dog image.

import RandomDog from './newDog';

Steps to create the RandomDog component

  • [x] Create a component where image URL is an empty string
  • [x] Upon mount, fetch a random dog photo and save its URL in our state
  • [x] That's it, the component re-renders because of the state change, and shows the image using the URL in the state

Creating RandomDog component using useEffect

import React, { useState, useEffect } from 'react';
 
export default function RandomDog() {
  const [url, setUrl] = useState('a');
 
  // The useEffect `here` does the job of componentDidMount
  useEffect(() => {
    fetch('https://dog.ceo/api/breeds/image/random')
      .then((res) => res.json())
      .then((data) => setUrl(data.message));
  }, []);
 
  return <img src={url} alt="a random dog" />;
}

The above component can be written using the old componentDidMount as follows:

import React from 'react';
 
class RandomDog extends React.Component {
  state = {
    url: ''
  };
 
  componentDidMount() {
    fetch('https://dog.ceo/api/breeds/image/random')
      .then((res) => res.json())
      .then((data) => this.setState({ url: data.message }));
  }
 
  render() {
    return <img src={this.state.url} alt="dog picture" />;
  }
}

Comments