React & State Management: All Concepts
Section 1: Fundamentals 1. Counter with increment, decrement, reset — useState Remember: prev is needed when the new state depends on the old state. When you're setting a hardcoded value like 0, you just pass 0 directly. Why: reason prev matters — if multiple state updates happen in the same render cycle, React batches them. Using prev guarantees you're working off the latest state, not a stale snapshot. 2. Toggle show/hide paragraph — useState Remember: onClick={toggle} — pass the function reference, not the call. onClick={() => toggle()} — also fine, arrow function that calls toggle when clicked. onClick={toggle()} — calls toggle immediately during render, setVisible triggers re-render, toggle calls again, infinite loop. Why: JSX evaluates expressions inside {} during render. toggle() is an expression that executes immediately. React doesn't get a chance to attach it as a handler — it just runs it right there, state updates, component re-renders, runs again. ...