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 (
    <>
      
         setCount((count) => count + 1)}>
          count is {count}
        
         setCount((count) => count = 0)}>
          Reset
        
      
    >
  );
}

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:

setCount((count) => count = 0)}>
  Reset

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:

setCount(0)}>
  Reset

App in action

Image description

Post reset

Image description