Validates against unconditionally setting state during render, which can trigger additional renders and potential infinite render loops.
Rule Details
CallingsetState during render unconditionally triggers another render before the current one finishes. This creates an infinite loop that crashes your app.
Common Violations
Invalid
// ❌ Unconditional setState directly in render
functionComponent({value}){
const[count,setCount] =useState(0);
setCount(value);// Infinite loop!
return<div>{count}</div>;
}Valid
// ✅ Derive during render
functionComponent({items}){
constsorted =[...items].sort();// Just calculate it in render
return<ul>{sorted.map(/*...*/)}</ul>;
}
// ✅ Set state in event handler
functionComponent(){
const[count,setCount] =useState(0);
return(
<buttononClick={()=>setCount(count +1)}>
{count}
</button>
);
}
// ✅ Derive from props instead of setting state
functionComponent({user}){
constname =user?.name ||'';
constemail =user?.email ||'';
return<div>{name}</div>;
}
// ✅ Conditionally derive state from props and state from previous renders
functionComponent({items}){
const[isReverse,setIsReverse] =useState(false);
const[selection,setSelection] =useState(null);
const[prevItems,setPrevItems] =useState(items);
if(items !==prevItems){// This condition makes it valid
setPrevItems(items);
setSelection(null);
}
// ...
}Troubleshooting
I want to sync state to a prop
A common problem is trying to “fix” state after it renders. Suppose you want to keep a counter from exceeding amax prop:
// ❌ Wrong: clamps during render
functionCounter({max}){
const[count,setCount] =useState(0);
if(count >max){
setCount(max);
}
return(
<buttononClick={()=>setCount(count +1)}>
{count}
</button>
);
}As soon ascount exceedsmax, an infinite loop is triggered.
Instead, it’s often better to move this logic to the event (the place where the state is first set). For example, you can enforce the maximum at the moment you update state:
// ✅ Clamp when updating
functionCounter({max}){
const[count,setCount] =useState(0);
constincrement =()=>{
setCount(current=>Math.min(current +1,max));
};
return<buttononClick={increment}>{count}</button>;
}Now the setter only runs in response to the click, React finishes the render normally, andcount never crossesmax.
In rare cases, you may need to adjust state based on information from previous renders. For those, followthis pattern of setting state conditionally.