React: Random Quote Generator useEffect Dependancies?

Hi all, I am hoping to find a solution to this warning message that I received:

Line 20:4: React Hook useEffect has missing dependencies: ‘randomObject.author’ and ‘randomObject.text’. Either include them or remove the dependency array react-hooks/exhaustive-deps

Below is my code:

import React, {useState, useEffect} from "react"
import './App.css';

function App() {
const [data, setData] = useState([])
const [quote, setQuote] = useState("")
const [author, setAuthor] = useState("")

const randomIndex = Math.floor(Math.random() * data.length)
const randomObject = data[randomIndex]

useEffect(() => {
  fetch("https://type.fit/api/quotes")
  .then(response => response.json())
  .then(data => {
    setData(data)
    setQuote(randomObject.text)
    setAuthor(randomObject.author)
  })
}, [])

const handleClick = () => {
  setQuote(randomObject.text)
  setAuthor(randomObject.author)
}

  return (
    <div className="container" id="quote-box">
      <h1 id="text">{quote}</h1>
      <h2 id="author">{author}</h2>
      <button onClick={(handleClick)}>New Quote</button>
    </div>
  );
}
export default App;

If anyone has a solution for this, I would love to hear about it. Thanks!

It will definitely help us help you if you post a link to your code for example on codepen :slight_smile:

Google “React Hook useEffect has missing dependencies” and you’ll get plenty of results that explain this. Here’s one that is relevant to your issue:

Hi, @anamariekl

In simple terms, useEffect is responsible for handling side effects.

As you probably know already, useEffect takes a function as the first argument and an array of dependencies as the second.

To use useEffect properly, you must always declare all the dependencies the first argument(function) has. In your case, it is randomObject. If you add this object, you will probably get an infinite loop as randomObject will be created on each render.

To avoid that, you can move the randomIndex and randomObject inside the useEffect so the array of the dependencies will stay empty.

Hi, thanks for the response! Okay, that was the issue that I was having actually when I added randomObject inside of the array, what you’re saying makes sense, and thank you!