Validates against assignment/mutation of globals during render, part of ensuring thatside effects must run outside of render.
Rule Details
Global variables exist outside React’s control. When you modify them during render, you break React’s assumption that rendering is pure. This can cause components to behave differently in development vs production, break Fast Refresh, and make your app impossible to optimize with features like React Compiler.
Invalid
Examples of incorrect code for this rule:
// ❌ Global counter
letrenderCount =0;
functionComponent(){
renderCount++;// Mutating global
return<div>Count:{renderCount}</div>;
}
// ❌ Modifying window properties
functionComponent({userId}){
window.currentUser =userId;// Global mutation
return<div>User:{userId}</div>;
}
// ❌ Global array push
constevents =[];
functionComponent({event}){
events.push(event);// Mutating global array
return<div>Events:{events.length}</div>;
}
// ❌ Cache manipulation
constcache ={};
functionComponent({id}){
if(!cache[id]){
cache[id] =fetchData(id);// Modifying cache during render
}
return<div>{cache[id]}</div>;
}Valid
Examples of correct code for this rule:
// ✅ Use state for counters
functionComponent(){
const[clickCount,setClickCount] =useState(0);
consthandleClick =()=>{
setClickCount(c=>c +1);
};
return(
<buttononClick={handleClick}>
Clicked:{clickCount} times
</button>
);
}
// ✅ Use context for global values
functionComponent(){
constuser =useContext(UserContext);
return<div>User:{user.id}</div>;
}
// ✅ Synchronize external state with React
functionComponent({title}){
useEffect(()=>{
document.title =title;// OK in effect
},[title]);
return<div>Page:{title}</div>;
}