Why You Should Avoid Using count = 0 in React State Updates
React is known for its declarative nature, which allows developers to focus on describing what the UI should look like at any given point in time rather than dealing with the nitty-gritty of how the UI updates.
Consider an example
import { useState } from 'react';
import './App.css';
function App() {
const [count, setCount] = useState(0);
return (
<>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<button onClick={() => setCount((count) => count = 0)}>
Reset
</button>
</div>
</>
);
}
export default App;
At first glance, this code works perfectly. It has a button to increment the counter and a button to reset it to zero. However, take a moment to look at the reset button:
<button onClick={() => setCount((count) => count = 0)}>
Reset
</button>
Why setCount(0)
is Better
Instead of writing count = 0
, it’s much clearer and simpler to write setCount(0)
. Here’s the updated code:
<button onClick={() => setCount(0)}>
Reset
</button>
App in action
Post reset
Top comments (0)