Using React Hooks For Loading Screen

Joe C Gomez
2 min readMay 10, 2021

A loading screen is a great way to let users know something is happening on the page or have them wait while something is fetching. It doesn’t let them think the page just crashed, giving them some sort of confirmation when they see that spinning icon.

For our walkthrough, we are going to be building A “LOADING” screen when we’re fetching to an API.

Here’s out boiler plate code!

import { useState, useEffect } from 'react'const App = () => {  return (    <div>    </div>  )
}
export default App;

If you do not know useState or useEffect you can checkout my blogs about them!

useState: https://devjoe.medium.com/implementing-react-hooks-usestate-53e565669439

useEffect: https://devjoe.medium.com/implementing-react-hooks-useeffect-e27b7a81c74e

I’m going to be call on a dummy API from https://jsonplaceholder.typicode.com/

First we need to create an empty array in order to put our users data and loading state of false.

const [users, setUsers] = useState([])const [loading, setLoading] = useState(false)

Let’s fetch to the API using useEffect, update our loading state to true, and create a setTimeout function that has another function (handleUsers).

useEffect(() => {  fetch('https://jsonplaceholder.typicode.com/users')  .then(setLoading(true))  .then(res => res.json())  .then(users => setTimeout(() => handleUsers(users), 3000))}, [])

handleUsers function is going to set the user data inside that array we created and update our loading to false.

const handleUsers = (users) => {  setUsers(users)  setLoading(false)}

Then in our JSX we are going to use a ternary operator.

return (  <div className="App">    {loading ? startLoading : userContainer }  </div>);

Our startLoading and userContainer variables is going to return this.

let startLoading = (  <h1> LOADING </h1>)let userContainer = (  <>    {users.map(user => <ul><p> {user.name} </p></ul>)}  </>)

That’s everything, thank yo for reading! You can of course checkout my code here on my GitHub!

https://github.com/JoeG21/medium-ex/tree/master/react-fetch-loading-screen

--

--

Joe C Gomez

Find some time to do something! 🧠 Flatiron Alumni 🏛