Skip to main content

Lifecycle Hooks: DidMount, WillMount, IsMounted, IsFirstRender

Best Practices Guide for React Lifecycle Utilities


Introduction

Archibald provides a suite of semantic hooks to handle common React lifecycle patterns. These hooks improve code readability and help avoid common pitfalls like updating state on unmounted components or incorrectly timing initial setup logic.

The Hooks

  • useDidMount: A semantic replacement for useEffect(cb, []).
  • useWillMount: Executes logic immediately before the first render pass.
  • useIsMounted: Returns a ref that tracks the component's mount status.
  • useIsFirstRender: Detects if the current render is the initial one.

How it works

These hooks use stable useRef and useEffect patterns internally:

  1. Mounting: useWillMount runs during the first call. useDidMount and useIsMounted (setting to true) run after the DOM is ready.
  2. Tracking: useIsFirstRender flips its internal flag after the first render completes.
  3. Cleanup: useIsMounted sets its flag to false in the useEffect cleanup function.

Advantages

  • Readability: useDidMount clearly signals "run once on start," unlike an empty dependency array which can be ambiguous to beginners.
  • Safety: useIsMounted is essential for preventing "state update on unmounted component" warnings in async operations.
  • Timing Control: useWillMount allows for synchronous setup that must happen before JSX is evaluated.

Disadvantages

  • Over-abstraction: Overusing these can make code feel "non-standard" to developers expecting pure React.
  • Misuse of useWillMount: Developers might mistakenly put heavy logic in useWillMount, blocking the initial render.

See Also

For a detailed technical breakdown and additional implementation patterns, refer to the following resources:


Key Takeaways

  • Use useIsMounted for all async operations: Always check isMounted.current before calling setState after an await or setTimeout.
  • Prefer useDidMount for subscriptions: Use it to set up event listeners or analytics tracking on component load.
  • Use useIsFirstRender for "Welcome" effects: Ideal for triggering one-time animations or walkthroughs that shouldn't repeat on subsequent re-renders.
  • Keep useWillMount lightweight: Only use it for essential synchronous configuration. Avoid data fetching here (use useFetch instead).
  • Don't forget cleanup: Even with useDidMount, if your callback returns a cleanup function, Archibald ensures it's handled correctly.