[React] Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
error

[React] Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

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

문제 해결 방법:

 

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

const Counter = () => {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log('effect')
    });

    return (
        <div>
            {count}
            <button onClick={setCount(count + 1)}>click</button>    // ERROR!!
        </div>
    )
}


ReactDOM.render(
    <Counter />,
    document.getElementById('root')
)

 

 

 

 

 

 위의 코드에서

 

 

 

 

 

<button onClick={setCount(count + 1)}>click</button>

 부분을

 

 

 

 

 

<button onClick={() => setCount(count + 1)}>click</button>

 로 수정하여 해결