DEV Community

alok-38
alok-38

Posted on

The Right Way to Reset State in React

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;

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

App in action

Image description

Post reset

Image description

Top comments (0)