Skip to main content
Not yet stable
@foresightjs/react is at 0.1.0 and not yet stable. It works and is fully tested, but the API may still change.
Version: 4.0

useForesightEvent

This is meant for high-level, app-wide use cases (analytics, debugging, a global prediction counter), not per-element logic. useForesightEvent subscribes a component to the ForesightManager events. Pass the event name and a listener, and the hook handles adding and removing the listener for you.

import { useState } from "react"
import { useForesightEvent } from "@foresightjs/react"

function PrefetchCounter() {
const [hits, setHits] = useState(0)

useForesightEvent("callbackInvoked", event => {
setHits(count => count + 1)
})

return <p>{hits} prefetches triggered</p>
}

The listener is always called with the latest closure, so you can reference state and props inside it without re-subscribing. You don't need to remove the listener yourself, the hook does it for you when the component unmounts (or when the event name changes).

See Events for the full list of event names and their payloads.