0

I've always thought that having any form of setState inside a useEffect call would result in an infinite re-render loop due to the useEffect being called on each render. But for some reason my code is fine and my Next.js application runs perfectly. Could I know what the gaps in my knowledge are?

const [base, setBase] = useState(DEFAULT_BASE)
const [rateData, setRateData] = useState([])
const [symbolList, setSymbolList] = useState([])

// At the start, we want to display the rates in terms of EUR
useEffect(async () => {
  const data = await calculator(FETCH_DATA, base)
  setRateData(data)
  // Create the symbol list
  const symbols = []
  Object.keys(data).map((c) =>
    symbols.push(c)
  )
  setSymbolList(symbols)
  console.log(symbolList)
}, [])
Adam Lau
  • 153
  • 2
  • 10
  • Your `useEffect` has empty dependencies, so why do you expect it to re-run? (disclaimer: I am not saying, that what you are doing is good or bad design-wise) – ASDFGerte Mar 19 '21 at 15:33
  • it will only run on every render if you omit the second parameter (no empty array). – Chris Mar 19 '21 at 15:38
  • 1
    Something unrelated but Don't use async for `useEffect` function. useEffect expects either nothing or a function to be returned which is usually known as a cleanup function. By writing `async` its returning a Promise. Refer this https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret – Rajiv Punjabi Mar 19 '21 at 15:45
  • Does this answer your question? [In useEffect, what's the difference between providing no dependency array and an empty one?](https://stackoverflow.com/questions/58579426/in-useeffect-whats-the-difference-between-providing-no-dependency-array-and-an) – Zsolt Meszaros Mar 19 '21 at 17:55

1 Answers1

2

You have an empty array as an arg at the end.

UseEffect with an empty [] dependency array means that will only only run when the componentDidMount, this is only done when the component loads for the first time.

Not passing that argument will cause it to be called when any state variable is changed and one every re-render (similar to your expectation).

If you pass a variable to the array, then it will be called only when that variable changes. You can have more than one useEffect functions as well, so you can selectively render as well.

Read the Note here: https://reactjs.org/docs/hooks-effect.html

Ravi L
  • 1,142
  • 9
  • 17