skip to Main Content

I was experimenting with react. and used setState as shown below.

import {useState} from 'react';
export default function App() {
  const [state,setState]=useState([]);

  const fetchApi= async()=>{
    return fetch('https://jsonplaceholder.typicode.com/posts')
                .then(response=>response.json())
                .then(data=>{console.log(data); return data})
                .catch(err=>console.log(err))
  }
  setState(fetchApi());
  return (
    <div>
    </div>
  );
}

In above code, setState is called again and again(infinitely). Can you please provide some explanation what exactly is happening behind the scene?

I know this is not the way of making an API call. One should always use useEffect to fetchdata and set the state accordingly. But I am curious about this one.

2

Answers


  1. According to 3 ways to cause an infinite loop in React

    If you update the state directly inside your render method or a body
    of a functional component, it will cause an infinite loop.

    State updates → triggers re-render → state updates → triggers
    re-render → …

    So you should never update the state directly inside your render method or a functional component.

    Instead, you should use useEffect hook to fetch data and update the state accordingly.

    For example:

    useEffect(() => {
      fetchApi().then((data) => setState(data));
    }, []);
    
    Login or Signup to reply.
  2. you are calling "setState" in the body of the compnent, what will happen is : the compnent will render, and while rendering it will call setState which will update the state and force the component to rerender which in turn will set the state again and force the component to rerender and so forth, and you will be caught in an infinite loop;
    to get arround this wrap the set state in a useEffect hook

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search