Home

Demo of componentDidMount using useEffect, using API

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.

Steps to create the RandomDog component

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" />;
  }
}


Last Updated on

Next Post: Rules vs Guidelines →

Comments