Foresight
<Foresight/> is an experimental feature, so this interface may change.
This is a component that uses js.foresight to predict user interactions based on mouse trajectory, keyboard navigation, and scroll behavior. It enables proactive prefetching and UI optimization before users actually interact with elements.
The Foresight component integrates with the
js.foresight library to provide predictive
interaction detection. This allows you to trigger callbacks before users
actually click or interact with elements, enabling smart prefetching
strategies.
import { PrefetchQuery } from '@suspensive/react-query'
import { Foresight } from '@suspensive/react-dom'
const PostsPage = ({ posts }: { posts: Post[] }) => (
<div>
<h1>Posts</h1>
{posts.map((post) => (
<Foresight
key={post.id}
callback={() => {
// This will be called when user is likely to interact with the element
console.log(`User is likely to click on post ${post.id}`)
}}
name={`post-${post.id}`}
hitSlop={10}
>
{({ ref, isRegistered }) => (
<div ref={ref}>
{isRegistered && (
<PrefetchQuery
queryKey={['posts', post.id, 'comments']}
queryFn={() => getPostComments(post.id)}
/>
)}
<h2>{post.title}</h2>
<p>{post.description}</p>
<Link to={`/posts/${post.id}/comments`}>See comments</Link>
</div>
)}
</Foresight>
))}
</div>
)props.callback
callback is a function that is called when the user is predicted to interact with the element. This happens before the actual interaction occurs.
props.hitSlop
hitSlop expands the interaction detection area around the element. It can be a number (for all sides) or an object specifying different values for each side.
props.name
name is an optional identifier for the registered element, useful for debugging and analytics.
props.meta
meta is an optional object for storing additional information about the registered element.
props.reactivateAfter
reactivateAfter sets the time in milliseconds after which the callback can be fired again. Default is Infinity (callback only fires once).
props.disabled
disabled prevents the element from being registered with foresight tracking.