-1

Why does the code below end up in an infinite loop? I believe that the same data is brought by fetch and set it to starWarData. So, the value in the dependency array should be the same between renders.

    React.useEffect(function() {
        fetch("https://swapi.dev/api/people/1")
            .then(res => res.json())
            .then(data => setStarWarsData(data))
    }, [starWarsData])
    
    return (
        <div>
        {console.log("render")}
            <pre>{JSON.stringify(starWarsData, null, 2)}</pre>
            <h2>The count is {count}</h2>
            <button onClick={() => setCount(prevCount => prevCount + 1)}>Add</button>
        </div>
    )

Code sample: https://scrimba.com/scrim/co3f04cbe8393c8d93714e7cd

Artur A
  • 7,115
  • 57
  • 60
Si Thu
  • 33
  • 2

1 Answers1

1

The useEffect hook has a dependency array that includes the starWarsData variable, which is being updated inside useEffect hook.
Therefore, you should remove startWars from line 16:

import React from "react"

export default function App() {
    const [starWarsData, setStarWarsData] = React.useState({})
    const [count, setCount] = React.useState(0)

/**
 * Quiz:
 * 1. What will happen if I put back our Star Wars API call
 *    into the effect function?
 */
React.useEffect(function() {
    fetch("https://swapi.dev/api/people/1")
        .then(res => res.json())
        .then(data => setStarWarsData(data))
}, [])

return (
    <div>
    {console.log("render")}
        <pre>{JSON.stringify(starWarsData, null, 2)}</pre>
        <h2>The count is {count}</h2>
        <button onClick={() => setCount(prevCount => prevCount + 1)}>Add</button>
    </div>
)
}
Uri Loya
  • 1,181
  • 2
  • 13
  • 34