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 foruseEffect(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:
- Mounting:
useWillMountruns during the first call.useDidMountanduseIsMounted(setting totrue) run after the DOM is ready. - Tracking:
useIsFirstRenderflips its internal flag after the first render completes. - Cleanup:
useIsMountedsets its flag tofalsein theuseEffectcleanup function.
Advantages
- Readability:
useDidMountclearly signals "run once on start," unlike an empty dependency array which can be ambiguous to beginners. - Safety:
useIsMountedis essential for preventing "state update on unmounted component" warnings in async operations. - Timing Control:
useWillMountallows 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 inuseWillMount, blocking the initial render.
See Also
For a detailed technical breakdown and additional implementation patterns, refer to the following resources:
Key Takeaways
- Use
useIsMountedfor all async operations: Always checkisMounted.currentbefore callingsetStateafter anawaitorsetTimeout. - Prefer
useDidMountfor subscriptions: Use it to set up event listeners or analytics tracking on component load. - Use
useIsFirstRenderfor "Welcome" effects: Ideal for triggering one-time animations or walkthroughs that shouldn't repeat on subsequent re-renders. - Keep
useWillMountlightweight: Only use it for essential synchronous configuration. Avoid data fetching here (useuseFetchinstead). - Don't forget cleanup: Even with
useDidMount, if your callback returns a cleanup function, Archibald ensures it's handled correctly.