Compatibility rules
- React course
- Expert
- Lesson 3/32
- 4 min
Learn the rules for writing compiler-friendly code.
Compatibility: pure render
The React Compiler expects components to be pure. No side effects during render: calling Math.random(), mutating a global variable or writing to the DOM directly breaks the compiler.
Side effects go into useEffect. State is updated with setState and read during render.
Hooks must always be called in the same order; never inside a condition.
Hook order
React tracks hooks by call order. If you call useState inside an if the order breaks and you get a runtime error.
The correct way: call the hook at the top, then apply conditional behaviour with if. The useEffect dependency array is evaluated in the same order.
The compiler checks this pattern automatically and warns on violations.
Practice Write the Counter component
Write Counter. Keep count with useState(0). Inside useEffect set document.title = count with dependency [count]. Return <button onClick={() => setCount(count + 1)}>{count}</button>. Export it.
Starter code
import { useState, useEffect } from 'react';
// Write the Counter component hereSample solution
import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = count;
}, [count]);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
export default Counter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match pure render behaviours
| Term | Meaning |
|---|---|
Math.random |
Side effect, not called |
useEffect |
Side effects here |
setState |
Updates state |
condition |
No hook inside |
2 Which of the following is safe during render?
- Setting document.title
- Calling Math.random()
- Mutating a global variable
- Updating with setState Correct answer
Explanation: setState can be called in render; it is not a side effect.
3 Fill in the blank: useEffect dependency
useEffect(() => {
document.title = count;
}, ____);
useEffect(() => {
document.title = count;
}, [count]);
Explanation: The dependency array is written in square brackets.