Validates thatcomponents/hooks are pure by checking that they do not call known-impure functions.
Rule Details
React components must be pure functions - given the same props, they should always return the same JSX. When components use functions likeMath.random() orDate.now() during render, they produce different output each time, breaking React’s assumptions and causing bugs like hydration mismatches, incorrect memoization, and unpredictable behavior.
Common Violations
In general, any API that returns a different value for the same inputs violates this rule. Usual examples include:
Math.random()Date.now()/new Date()crypto.randomUUID()performance.now()
Invalid
Examples of incorrect code for this rule:
// ❌ Math.random() in render
functionComponent(){
constid =Math.random();// Different every render
return<divkey={id}>Content</div>;
}
// ❌ Date.now() for values
functionComponent(){
consttimestamp =Date.now();// Changes every render
return<div>Created at:{timestamp}</div>;
}Valid
Examples of correct code for this rule:
// ✅ Stable IDs from initial state
functionComponent(){
const[id] =useState(()=>crypto.randomUUID());
return<divkey={id}>Content</div>;
}Troubleshooting
I need to show the current time
CallingDate.now() during render makes your component impure:
// ❌ Wrong: Time changes every render
functionClock(){
return<div>Current time:{Date.now()}</div>;
}Instead,move the impure function outside of render:
functionClock(){
const[time,setTime] =useState(()=>Date.now());
useEffect(()=>{
constinterval =setInterval(()=>{
setTime(Date.now());
},1000);
return()=>clearInterval(interval);
},[]);
return<div>Current time:{time}</div>;
}