Skip to main content

useMounted

The useMounted hook tracks whether a component is currently mounted to the DOM. It returns false initially and on unmount, and true when the component is mounted. This is useful for preventing state updates on unmounted components.

Installation

Import

Usage

Returns

boolean
A boolean value that is false initially and on unmount, and true when the component is mounted.

Type Definition

Examples

Preventing Memory Leaks

Delayed Actions

Animation Delays

Conditional Event Listeners

WebSocket Connection

Polling Data

Form Submission

Common Patterns

Safe State Updates

Wrap state updates in mounted checks:

Cleanup Pattern

Use with cleanup functions:

Custom Async Hook

Use Cases

  • Preventing state updates after component unmounts
  • Avoiding “Can’t perform a React state update on an unmounted component” warnings
  • Safely handling async operations (fetch, setTimeout, setInterval)
  • Managing WebSocket connections
  • Controlling animations and transitions
  • Conditional event listener attachment
  • Polling and real-time data updates

Notes

  • The hook returns false on initial render and after unmount
  • The hook returns true after the component mounts (after useEffect runs)
  • This pattern helps prevent memory leaks and React warnings
  • Always check the mounted value before calling state setters in async callbacks
  • The cleanup function automatically sets mounted to false
  • This is particularly useful for components that fetch data or use timers
  • Consider using AbortController for fetch requests as an alternative cancellation method