by activitypea · 3y ago · 0 comments
The quickest obstacle you’ll run into as someone new to React will be something like this
function MyComponent() {
const [num, setNumber] = useState(42);
// infinite loop
setNumber(n => n + 1);
return <div>{num}</div>
}Trying to make state updates at the top level of a component will result in an infinite loop.
```
I've taught React to dozens of people without ever seeing someone try this. A render function is an idempotent function that produces UI for a given state, and it's called every time the state changes. What are you, semantically, trying to do by updating state midway through a render function? This isn't a footgun, this is the author picking up a screwdriver and going "I wonder what happens if I press it against my eyeball"
I like how you say "others might not be so diligent to have read the docs"... As opposed to? Picking up a UI framework and just winging your way through LSP autocompletions until something happens on your screen?
Yes, that, and following bad tutorials by other people who did the same.