Q:

Loading state in react: Too many re-renders. React limits the number of renders to prevent an infinite loop

How do I prevent the following error:

Too many re-renders. React limits the number of renders to prevent an infinite loop.'

My code:
function App() {
    const [items, setItems] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    if (items.length == 0) loadMore()
    return <div>
        {isLoading
            ? <div>Loading...</div>
            : <ol>{items.map(i => <li>{i}</li>)}</ol>
        }
        <button disabled={isLoading} onClick={loadMore} style={{ width: "100%" }}>
            {isLoading ? "Loading..." : "Load again"}
        </button>
    </div>;

    function loadMore() {
        setIsLoading(true); // ⚠ errors!
        const uri = "https://www.reddit.com/r/reactjs.json";
        fetch(uri)
            .then(r => r.json())
            .then(r => {
                const newItems = r.data.children.map(i => i.data.title);
                items.push(...newItems);
                setItems([...items]);
                setIsLoading(false);
            });
    }
}

Stackblitz link.

A:

That's because of this condition if (items.length == 0) loadMore().
Because at the beginning the length is 0, loadMore is called in which you set the state and you enter the condition again which call loadMore and so on.
Use the useEffect hook with an empty array of dependencies instead of the condition which will call the function once when the component mount.
useEffect(loadMore, [])

