Skip to content

Latest commit

 

History

History
33 lines (26 loc) · 788 Bytes

use-mounted-ref.md

File metadata and controls

33 lines (26 loc) · 788 Bytes

useMountedRef hook

A React hook that returns a ref object returns true when component is mounted and false otherwise. It might be useful in case you are unable to cancel async operation, e.g. your api client doesn't support cancellation.

Usage

import {useMountedRef} from '@itshkins/react-utils'

const EntityForm = () => {
  const mounted = useMountedRef()

  const submit = useCallback((evt) => {
      const data = new FormData(evt.target)

      apiClient
        .createEntity(data)
        .then(() => {
          if (mounted.current) {
            // do something
          }
        })
        .catch(() => {
          if (mounted.current) {
            // do something
          }
        })
  )}, [mounted])

  return <form onSubmit={submit} />
}