Skip to content

Commit 86e7156

Browse files
committed
docs: clarify that immutability lint rule does not flag method mutations without inferred types
The immutability lint documentation previously listed array push() and sort() under 'Invalid' examples as if the rule flagged them. However, per react/react#35157, eslint-plugin-react-hooks only produces diagnostics on property assignments unless the compiler can infer the type. This updates the examples to present property assignment as the verified invalid example and adds an explanatory Note explaining why method mutations do not emit a diagnostic while remaining bad practice. Fixes #8758
1 parent 46a54e0 commit 86e7156

1 file changed

Lines changed: 7 additions & 18 deletions

File tree

‎src/content/reference/eslint-plugin-react-hooks/lints/immutability.md‎

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,6 @@ A component’s props and state are immutable snapshots. Never mutate them direc
1717
### Invalid {/*invalid*/}
1818

1919
```js
20-
// ❌ Array push mutation
21-
function Component() {
22-
const [items, setItems] = useState([1, 2, 3]);
23-
24-
const addItem = () => {
25-
items.push(4); // Mutating!
26-
setItems(items); // Same reference, no re-render
27-
};
28-
}
29-
3020
// ❌ Object property assignment
3121
function Component() {
3222
const [user, setUser] = useState({name: 'Alice'});
@@ -36,16 +26,15 @@ function Component() {
3626
setUser(user); // Same reference
3727
};
3828
}
29+
```
3930

40-
// ❌ Sort without spreading
41-
function Component() {
42-
const [items, setItems] = useState([3, 1, 2]);
31+
<Note>
4332

44-
const sortItems = () => {
45-
setItems(items.sort()); // sort mutates!
46-
};
47-
}
48-
```
33+
#### Note on Array and Method Mutations {/*array-and-method-mutations*/}
34+
35+
Direct property mutations (like `user.name = 'Bob'`) are caught and flagged by this rule. However, calling mutating methods like `items.push(4)` or `items.sort()` will not produce a linter diagnostic unless the compiler can fully infer the state type. Even if the linter does not flag them, you must avoid in-place mutations because passing the same object/array reference to a state setter prevents React from triggering re-renders.
36+
37+
</Note>
4938

5039
### Valid {/*valid*/}
5140

0 commit comments

Comments
 (0)