one-hook
Size
0.41 kb
View source

useMutationObserver

The MutationObserver API, reactified and simplified

Installation

npm install @1hook/use-mutation-observer

Usage

import {  } from '@1hook/use-mutation-observer'

Observe an element’s child list mutation:

function () {
  const {  } = (
    () => .("The element's child list has changed!"),
    { : true },
  )

  return < ={} />
}

Manual observation control:

function () {
  const { , ,  } = (
    () => .("The element's child list has changed!"),
    { : true, : false }, // Disable automatic observation
  )

  return (
    <>
      < ={} />

      < ={}>Start observing</>

      < ={}>Stop observing</>
    </>
  )
}

API Reference

UseMutationObserverOptions

The options for the useMutationObserver hook. See MDN docs for more details.

PropTypeDefault
autoObserve?
boolean
true
subtree?
boolean
-
childList?
boolean
-
characterDataOldValue?
boolean
-
characterData?
boolean
-
attributes?
boolean
-
attributeOldValue?
boolean
-
attributeFilter?
string[]
-

UseMutationObserverReturn

The return value of the useMutationObserver hook.

PropTypeDefault
target
Element | null
-
ref
Function
-
unobserve
() => void
-
observe
() => void
-

On this page