react-hooks/immutability
eslint-plugin-react-hooks
import reactHooks from "eslint-plugin-react-hooks";
export default [
{
plugins: { "react-hooks": reactHooks },
rules: {
"react-hooks/immutability": "error",
},
},
];Validates against mutating props, state, and other values that are immutable
function Component() {
const [items, setItems] = useState([1, 2, 3]);
const addItem = () => {
items.push(4); // Mutating!
setItems(items); // Same reference, no re-render
};
}function Component() {
const [user, setUser] = useState({name: 'Alice'});
const updateName = () => {
user.name = 'Bob'; // Mutating!
setUser(user); // Same reference
};
}function Component() {
const [items, setItems] = useState([3, 1, 2]);
const sortItems = () => {
setItems(items.sort()); // sort mutates!
};
}function Component() {
const [items, setItems] = useState([1, 2, 3]);
const addItem = () => {
setItems([...items, 4]); // New array
};
}function Component() {
const [user, setUser] = useState({name: 'Alice'});
const updateName = () => {
setUser({...user, name: 'Bob'}); // New object
};
}function TodoList() {
const [todos, setTodos] = useState([]);
const addTodo = (id, text) => {
setTodos([...todos, {id, text}]);
// Or: setTodos(todos => [...todos, {id: Date.now(), text}])
};
return (
<ul>
{todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
</ul>
);
}Examples from the ESLint documentation.
react-hooks/immutability
eslint-plugin-react-hooks
import reactHooks from "eslint-plugin-react-hooks";
export default [
{
plugins: { "react-hooks": reactHooks },
rules: {
"react-hooks/immutability": "error",
},
},
];react/immutability
react plugin · correctness
{
"plugins": [
"react"
],
"rules": {
"react/immutability": "error"
}
}Biome does not have this rule.
Validates against assignment/mutation of globals during render, part of ensuring that side effects must render outside of render
Validates against usage of libraries which are incompatible with memoization (manual or automatic)
Validates usage of error boundaries instead of try/catch for errors in child components
Validates that existing manual memoized is preserved by the compiler. React Compiler will only compile components and hooks if its inference matches or exceeds the existing manual memoization
Validates that components/hooks are pure by checking that they do not call known-impure functions
Validates correct usage of refs, not reading/writing during render. See the "pitfalls" section in useRef() usage