Skip to content

[Mistake]: set-state-in-effect gives a wrong example of bad usage #8411

Description

@zjlovezj

Summary

### I want to sync state to a prop {/*clamp-state-to-prop*/}
A common problem is trying to "fix" state after it renders. Suppose you want to keep a counter from exceeding a `max` prop:
```js
// ❌ Wrong: clamps during render
function Counter({max}) {
const [count, setCount] = useState(0);
if (count > max) {
setCount(max);
}
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
```
As soon as `count` exceeds `max`, an infinite loop is triggered.

Page

https://react.dev/reference/eslint-plugin-react-hooks/lints/set-state-in-render

Details

I want to sync state to a prop {/clamp-state-to-prop/}

A common problem is trying to "fix" state after it renders. Suppose you want to keep a counter from exceeding a max prop:

// ❌ Wrong: clamps during render
function Counter({max}) {
  const [count, setCount] = useState(0);

  if (count > max) {
    setCount(max);
  }

  return (
    <button onClick={() => setCount(count + 1)}>
      {count}
    </button>
  );
}

As soon as count exceeds max, an infinite loop is triggered.

I think this Counter component can be rendered and clicked without issues.
The claim that an infinite loop will be triggered is incorrect.

Activity

  1. justismailmemon commented on Apr 17, 2026

    @justismailmemon

    Thanks for reporting this. I opened a PR to clarify the wording: #8413

  2. Assamee commented on Apr 17, 2026

    @Assamee

    Hi! I’ve opened PR #8412 to address this.

    I verified the behaviour locally: while it doesn't cause a literal infinite loop (the condition eventually becomes false), it interrupts the current render and forces React to start over, which impacts performance. I've updated the wording to clarify this behaviour rather than focusing on the infinite loop claim.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions