AI summary by TwinMind

Unintuitive behaviors of React Hooks

Theo - t3․gg

16m 26s

Sponsor Segment - Epic React by Kent Dodds

  • Tutorial platform by Kent Dodds for React learning
  • Covers React 19 and foundational concepts
  • Interactive workshop format using local development environment
  • Clone repo and run locally in your own editor
  • Live community features with Discord integration
  • Company sponsorship option available with template letter

Initial Problem Setup

  • Question about unexpected behavior in React ref usage
  • Example: count button with previous value tracking
  • Counter increments, previous should show one behind
  • Code appears it shouldn't work but behaves correctly

Basic Implementation with useRef

  • const previous = useRef<number>(-1)
  • useEffect runs when count changes: previous.current = count
  • Renders previous.current in UI
  • Works despite appearing counterintuitive

React Execution Order Explanation

  • State change occurs first (count increments)
  • Component re-renders with new state
  • useEffect runs AFTER render completes
  • Console logging demonstrates: "rendering with X" before "updating with X"
  • Effects run after render to show user changes quickly

Batching State Updates

  • Alternative approach: batch updates in click handler
  • setPrev(count); setCount(count + 1)
  • Updates happen simultaneously in single render cycle
  • Moving ref update to click handler keeps everything in sync

Force Update Demonstration

  • const [, forceUpdate] = useState(-1)
  • Calling forceUpdate(Math.random()) triggers additional render
  • Ref stays current because multiple renders occur
  • Proves ref only holds "previous" value between render and effect

Core Problem with Ref Approach

  • previous.current isn't actually previous most of the time
  • Only truly previous between render and effect execution
  • After effect runs, ref contains current value
  • Logging current state shows both values are identical
  • UI displays outdated information during render

Effect Cleanup Function Solution

  • Return function from useEffect for cleanup
  • Cleanup runs before effect on state changes
  • Order: cleanup → render → effect
  • console.log demonstrates execution sequence
  • Cleanup fires when count dependency changes

useLayoutEffect Clarification

  • Runs between render generation and browser paint
  • Does NOT run before render like some expect
  • Still results in outdated values for this use case
  • Performance impact due to blocking browser repaint
  • Niche use case for DOM manipulation before paint

Custom Hook Implementation

function usePrevious<T>(value: T) {
  const [prev, setPrev] = useState<T>(value);
  useEffect(() => {
    setPrev(value);
  }, [value]);
  return prev;
}
  • Encapsulates logic in reusable hook
  • Clearer intent than raw useEffect
  • Recommended pattern for complex effects

Library Solutions Comparison

  • react-use library: uses ref approach (problematic)
  • UI.dev usehooks: better implementation without useEffect
  • Uses state batching instead of effects
  • Avoids render interruption issues
  • More performant and reliable

State Batching vs Effects

  • Multiple useState calls batch into single render
  • Effects interrupt render process
  • State batching approach eliminates timing issues
  • No "wrong render" scenarios
  • Cleaner execution model

TypeScript Considerations

  • UI.dev example has separate .d.ts file for types
  • Older pattern before inline TypeScript
  • Modern approach: write TypeScript directly
  • Type safety important for hook libraries

TwinMind

Get summaries like this for your own meetings

TwinMind takes notes in the background during meetings, lectures, and calls, then writes the summary for you.

Free plan to get started

No bot joins your calls

Phone, desktop & Chrome apps

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome