Search code examples
reactjsstateuse-stateanonymous-functioninline-functions

React gives a 301 error with inline functions but not with inline anonymous ones


This code generates a React error 301: https://reactjs.org/docs/error-decoder.html/?invariant=301

const [count, setCount] = useState(0)

return <>
    <p>{count}</p>
    <button onClick={setCount(count + 1)} >Increment count by 1</button>
</>

But if I run the setCount function inside a anonymous function I does not:

return <>
   <p>{count}</p>
    <button
        onClick = {() => {
            setCount(count + 1)
        }} 
    >Increment count by 1</button>
</>

Does anyone know why?


Solution

  • In the first example, every time the component renders it calls setCount (onClick is set to the return value of setCount(count + 1)). This call triggers a re-render. This is why you get that error.

    In the second case the call to setCount is deferrred until the button is clicked, thus not leading to a re-render on every render.