# React setState and Functional Updates to Avoid Direct Mutation

> Avoid modifying React component state directly by using setState with a callback function to prevent race conditions and ensure proper rerendering

**URL:** https://sentry.io/answers/modifying-state-directly/

---

## The Problem

The state of a component is managed internally by React. Updating the state of a component directly can have unintended consequences that can be difficult to debug.

```jsx
class Counter extends Component {
    constructor(props) {
        super(props)
        this.state = {
            counter: 0,
        }
    }

    increment() {
        this.state.counter = this.state.counter + this.props.increment
    }
}
```

If the state is updated directly as in the example above, the component will not rerender since the state is compared shallowly. Additionally, the update may be lost if there are other state changes queued asynchronously using setState.

Another common problem is using the current state/props to update the new state.

```jsx
class Counter extends Component {
    constructor(props) {
        super(props)
        this.state = {
            counter: 0,
        }
    }

    increment() {
        this.setState({
            counter: this.state.counter + this.props.increment
        })
    }
}
```

This will potentially cause issues due to a potential race condition between other state/prop changes and this particular state update. What happens if the props and/or state change before this state update happens?

## The Solution

The solution for the first example is to always use the `setState` function to ensure state changes are properly queued. For the second problem, React provides a different version of setState that takes a function instead of an object.

```jsx
class Counter extends Component {
    constructor(props) {
        super(props)
        this.state = {
            counter: 0,
        }
    }

    increment() {
        this.setState((prevState, props) => ({
            counter: prevState.counter + props.increment
        }))
    }
}
```

This will ensure that the state change happens with the correct version of the previous state and props.

### Using Functional Components with `useState`

In modern React, functional components with the [`useState`](https://react.dev/reference/react/useState) hook are the recommended way to manage state. The same counter looks like this:

```jsx
import { useState } from "react";

function Counter({ increment }) {
  const [counter, setCounter] = useState(0);

  function handleIncrement() {
    setCounter((prev) => prev + increment);
  }

  return <button onClick={handleIncrement}>{counter}</button>;
}
```

Passing a function to `setCounter` avoids the same stale-state problem described above: React calls the function with the current value, so the update is always based on the latest state.

### Further Reading

If you're looking to get a deeper understanding of how JavaScript error reporting works, take a look at the following articles:

- [Debug front end errors by giving Sentry more clues](https://blog.sentry.io/debug-tough-front-end-errors-sentry-clues/)
- [See how Aumni keeps errors out of userland](https://sentry.io/customers/aumni/)
- [Getting started with the React SDK (docs)](https://docs.sentry.io/platforms/javascript/guides/react/)

---

*Source: [sentry.io/answers/modifying-state-directly/](https://sentry.io/answers/modifying-state-directly/)*
