skip to Main Content

I’m building a simple React application where I update the state when a button is clicked. However, my component doesn’t re-render as expected when the state changes. Here is my code:

import React, { useState } from 'react';

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default App;

I expected the paragraph to update and display the new count each time I clicked the button, but it remains at 0. I’ve verified that the handleClick function is being called and setCount is executing.

2

Answers


  1. You need to use it as a callback function.

    <button onClick={() => handleClick() } >

    Login or Signup to reply.
  2. This seems to be working fine, but keep in mind that a correct state change that uses the previous value of the state should always be done using a callback function like so:

    const handleClick = () => {
        setCount((prevCount) => prevCount + 1);
      };
    

    If not done like this, you might get unexpected behaviours if that change is scheduled by React to be done in an async manner. Maybe that is what is causing you issues? Seems unlikely…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search