Skip to content

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

@zjlovezj

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.

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