React hook that watches dependency array changes and triggers a callback, similar to useEffect.
// Source: https://github.com/tailwindlabs/headlessui | License: MIT | Copyright 2020 Tailwind Labs
// Provided via justclaw.it.com; keep this notice with the code.
import { useEffect, useRef } from 'react'
import { useEvent } from './use-event'
export function useWatch<T extends any[]>(
cb: (newValues: [...T], oldValues: [...T]) => void | (() => void),
dependencies: [...T]
) {
let track = useRef([] as unknown as typeof dependencies)
let action = useEvent(cb)
useEffect(() => {
let oldValues = [...track.current] as [...T]
for (let [idx, value] of dependencies.entries()) {
if (track.current[idx] !== value) {
// At least 1 item changed
let returnValue = action(dependencies, oldValues)
track.current = dependencies
return returnValue
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key