ūüŹ° Home

React Hooks: Data Fetching on Component Mount with useEffect

With useEffect we can do data fetching when component is mounted. An example as follows:

import React, { useState, useEffect } from "react"
import "./styles.css"

export default function App() {
  const [users, setUsers] = useState([])

  const fetchUsers = async () => {
    const fetchResponse = await fetch(
      "https://jsonplaceholder.typicode.com/users",
      { method: "Get" }
    )
    const fetchData = await fetchResponse.json()
    setUsers(fetchData)
  }

  useEffect(() => {
    fetchUsers()
  }, [])

  return (
    <div className="App">
      <button onClick={fetchUsers}>Fetch Users</button>
      {users.map(user => (
        <p key={user.id}>{JSON.stringify(user)}</p>
      ))}
    </div>
  )
}

The useEffect without dependency will run the fetchUsers async function when the component mounted. A better way to write the useEffect here is by adding the fetchUsers function as dependency, this won't change the functionality but will be more inline with how the useEffect is used in React. So the useEffectwill be like this:

useEffect(() => {
  fetchUsers()
}, [fetchUsers])

Reference: