-1

I fixed a bug I had, but I'm not sure what specifically was wrong, or particularly what about it was going wrong. Below is the code before it started behaving.

This code caused the function to run every time the page re-rendered (which was a lot!). Here's the specific component that's getting called:

export const GetDBCards = () => {
const fetchDBCards = () => {
    
    fetch('http://localhost:3001/users')
    .then(res => res.json())
    .then(json => console.log(json))
}
return(
    <>
        <button onClick={fetchDBCards()}>Get Cards</button>
    </>
)

}

The only change was editing the actual function call in onClick to remove the parenthesis. My current (and expectantly) functional code for the line is this

<button onClick={fetchDBCards}> Get Cards</button>

What am I misunderstanding about the function call including the parenthetical?

dconnenc
  • 31
  • 6

2 Answers2

1

By including the parenthesis, you are calling the function during render, this means that you’re unconditionally executing it every times the component render. Instead you should pass the reference to the function and call it later on.

//  Wrong: calls the handler during render
return <button onClick={fetchDBCards()}>Click me</button>

// ✅ Correct: passes down the event handler
return <button onClick={fetchDBCards}>Click me</button>

// ✅ Correct: passes down an inline function
return <button onClick={() => fetchDBCards()}>Click me</button>
Reifocs
  • 704
  • 3
  • 16
1

JSX code in react gets converted to React.createElement() calls, so your

return(
  <button onClick={fetchDBCards()}>Get Cards</button>
)

is equivalent to

React.createElement(
  "button",
  { onClick: fetchDBCards() },
  "Get Cards"
);

The parentheses in javascript basically mean "execute this function", so you're telling react to make the value of onClick whatever the function result is, hence why the function executes every time you re-render the component.

By saying onClick={fetchDBCards} you're now passing the value of the const fetchDBCards, which is the function itself and not the result of that function (you can treat functions in javascript as normal variables and pass them around).

Internally, react will detect when you click the button and call the fetchDBCards function for you whenever the event occurs.

Simeon Borisov
  • 417
  • 2
  • 6