Using componentDidMount with React Hooks

hyeny
2 min readJun 22, 2021

--

While working on my project, I decided to pick up React Hooks. So I quickly taught myself how to implement what componentDidMount() renders in React Hooks with a functional component instead.

Using just React,

componentDidMount() {fetch("http://localhost:3000/applications").then(res => res.json()).then(appArray => this.setState({appCollection: appArray}))}

This chunk of code will go inside your class component, specifically right above its render().

With React Hooks, the syntax would be:

import React, { useEffect } from 'react'useEffect(() => {
// Put your mount code
}, []);

*don’t forget to import useEffect from react.

Using the example code at the top with its useState,

//In a functional componentconst [appCollection, updateApps] = useState({})
useEffect(() => {
fetch("http://localhost:3000/applications")
.then(res => res.json()).then(appArray => updateApps(appArray))
}, []);

By passing an empty array as a second argument, the useEffect() function will be executed exactly like the componentDidMount, which get executed on the first component rendering.

Thus, the code above will send a GET request and then ‘setState’ the appCollection with the new appArray upon loading that page first time.

  • To summarize, functions passed into useEffect() are executed whenever the component is rendered. However, you can pass a second argument such as an empty array to execute it once
  • You can also pass more values inside the array and the useEffect() function will run when those values change.

Resources:

--

--

hyeny
hyeny

No responses yet