A pure function returns the same value for the same inputs without reading outside state, randomness, or producing outside effects. In React, renders, initializers, effects, and state setters should remain pure so they can safely rerun when React schedules, replays, suspends, or restores work. section 3.1.2
Apply the purity rule to React code by checking whether each operation:
- Reads only its explicit inputs and permitted prior state, rather than a variable outside React’s scope. section 3.1.2
- Avoids changing external state during rendering, initialization, or calculation. section 3.1.2
- Produces an output that can be reused when the same inputs recur, which makes memoization meaningful. section 3.2
- Moves genuine external synchronization into an appropriately designed effect and cleanup rather than incrementing state merely because an effect ran. section 3.1.2
Strict Mode exposes impurity
A state initializer that reads and increments a module-level outsideCount is impure. Under Strict Mode, React invokes the initializer more than once, so the observed count diverges from production behavior. The same sample also updates state from an effect, demonstrating why rerunnable React code must not depend on one-time execution. section 3.1.2
Listing 3.3 A sample application with various effects
import { useEffect, useRef, useState } from "react";
let outsideCount = 0;
export default function App() {
const ref = useRef(true);
const [count, setCount] = useState(() => {
console.log( #1
"initializing count to", outsideCount #1
); #1
return outsideCount++;
});
console.log("rendering with ", count); #1
useEffect(() => {
console.log( #1
"effect first time?", ref.current #1
); #1
ref.current = false;
setCount((c) => {
console.log( #1
"setting count from ", c, " to ", c + 1 #1
); #1
return c + 1;
});
return () => console.log("cleaning up"); #1
}, []);
useEffect(() => {
console.log("effect every time?", count); #1
return () => console.log("cleaning up every time"); #1
}, [count]);
return <h1>What is the count? {count}</h1>;
}
Inspect the runnable sample to trace an external counter, repeated initialization, effect cleanup, and state updates through Strict Mode. section 3.1.2


















