How to run useEffect once and update data to useState before mounting

Viewed 29

I'm trying to call an API when the component mounts once. However, I can't do that without editing it to update the state after, as follows;

const [value, setValue] = useState(0)

const fetchData = async () => { 
  const data = await fetch(...)
  setValue(data)
}
useEffect(() => {
  fetchData()
}, [value]) // updating value useState

If I do that, I hit the API limit. The intended usage is for value to be updated but also run once.

1 Answers

In addition to what has been said in the comments (the dependencies array should be left empty), you should also be mindful that React Strict Mode will mount every component twice, to try and catch some bugs. This is done only in development mode and has no effect in production.

I would recommend you placing some console.logs in the component hooks and body to get a good idea of what function is being invoked and when.

Related