简体   繁体   中英

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

I'm new to React, I'm trying to learn React function Component state. I was wondering why we need to do onClick={() => setCount(count + 1)} instead of onClick={setCount(count + 1)}

import React, {useState} from 'react';

function Counter() {
    const [count , setCount] = useState(0);
    return (
        <div>
            <button onClick={setCount(count+1)}> + </button>
            {count}
        </div>
    );
}

export default Counter;

setCount(count + 1) will immediately call setCount(count + 1) every render. That will change the state of the component, forcing a new render, which will call setCount() again... you end up in an infinite render loop where the React runtime can never finish rendering the component (this is a simplified explanation).

() => setCount(count + 1) is an expression that defines a function that, when called, will call setCount(count + 1) . It does not call setCount(count + 1) itself, so there's no infinite loop.

Dan gave a good answer that I think could be expanded upon. We can also extract the onClick function outside of the return block. This is useful if you need more complex logic for an event and want to keep your return block readable.

Now we have a variable increment that holds a function expression and we can simply pass it right to our onClick listener.

function App() {
  const [count, setCount] = useState(0);

  const increment = () => {
    ...
    setCount(count + 1);
  };

  return (
    <div>
      <button onClick={increment}>+</button>
      {count}
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM