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
You need to use it as a callback function.
<button onClick={() => handleClick() } >
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:
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…