You are an expert software engineer specialised in Next.js 14 with TypeScript and TailwindCSS. I need you to build me a solution for constantly watching the visible HTML elements on my screen and extracting the ID of these visible elements. I’m assuming that this will be a hook. I want the values to dynamically update as user scrolls through the page, constantly monitoring the elements visible on their screen and updating the returned element IDs depending on real-time elements displayed on their screen. When building your solution ensure effectiveness, efficiency and best practice approaches. Ensure tidiness of code with best practice commenting.
Assistant
Certainly! Below is a comprehensive solution for creating a custom React hook named useVisibleElementIds using Next.js 14 with TypeScript and TailwindCSS. This hook leverages the IntersectionObserver API to monitor visible HTML elements on the screen and dynamically updates the list of their IDs as the user scrolls.
Overview
Hook Name: useVisibleElementIds
Purpose: Monitor and return a list of IDs of HTML elements currently visible in the viewport.
Technologies Used:
Next.js 14: For the React framework.
TypeScript: For type safety.
TailwindCSS: (Optional) For styling, if needed.
IntersectionObserver API: For efficiently observing visibility changes of elements.
Implementation
1. Creating the Custom Hook
typescript
// hooks/useVisibleElementIds.ts
import { useEffect, useState } from 'react';
/**
* Custom hook to monitor and return the IDs of HTML elements visible in the viewport.
*
* @returns {string[]} An array of visible element IDs.
*/
const useVisibleElementIds = (): string[] => {
const [visibleElementIds, setVisibleElementIds] = useState<string[]>([]);
useEffect(() => {
// Callback for IntersectionObserver
const callback: IntersectionObserverCallback = (entries) => {
setVisibleElementIds((prevVisibleIds) => {
const updatedVisibleIds = new Set(prevVisibleIds);
entries.forEach((entry) => {
const target = entry.target as HTMLElement;
const id = target.id;
if (!id) return; // Skip elements without an ID
if (entry.isIntersecting) {
updatedVisibleIds.add(id);
} else {
updatedVisibleIds.delete(id);
}
});
return Array.from(updatedVisibleIds);
});
};
// Options for the observer (you can adjust thresholds and rootMargin as needed)
const options: IntersectionObserverInit = {
root: null, // Defaults to the browser viewport
rootMargin: '0px',
threshold: 0.1, // Adjust to determine when the element is considered visible
};
// Create the IntersectionObserver instance
const observer = new IntersectionObserver(callback, options);
// Select all elements with an ID attribute
const elements: HTMLElement[] = Array.from(document.querySelectorAll('[id]'));
// Observe each element
elements.forEach((el) => observer.observe(el));
// Cleanup function to unobserve all elements
return () => {
elements.forEach((el) => observer.unobserve(el));
observer.disconnect();
};
}, []); // Empty dependency array ensures this runs once on mount
return visibleElementIds;
};
export default useVisibleElementIds;
2. Using the Custom Hook in a Component
Here's an example of how you can use the useVisibleElementIds hook within a Next.js page or component.
Efficiently monitors multiple elements without impacting performance.
The observer callback updates the state only when visibility changes occur.
State Management:
Uses useState to manage the list of visible element IDs.
Utilizes a Set to handle additions and removals, ensuring uniqueness.
Selecting Elements:
Observes all elements with an id attribute. If you want to target specific elements, adjust the selector accordingly (e.g., .track-visibility).
Performance Optimization:
The hook initializes the observer once (useEffect with an empty dependency array).
Cleans up by unobserving all elements and disconnecting the observer on unmount to prevent memory leaks.
Flexibility:
threshold can be adjusted depending on how much of the element should be visible before it's considered "visible".
rootMargin can be modified to include elements slightly outside the viewport.
TypeScript:
Provides type safety, ensuring that only elements with an id are processed.
Enhances code reliability and maintainability.
Styling with TailwindCSS:
The VisibleElementsTracker component uses Tailwind classes for styling. Adjust as necessary to fit your design requirements.
Additional Considerations
Debouncing State Updates:
For extremely frequent visibility changes, consider debouncing the state updates to minimize re-renders.
Handling Dynamic Content:
If the list of elements changes dynamically (e.g., elements are added or removed), you might need to adjust the hook to observe new elements. This can be achieved by adding dependencies or utilizing Mutation Observers.
Server-Side Rendering (SSR):
Since IntersectionObserver interacts with the window object, ensure that the hook is only used on the client-side. The current implementation inherently handles this by using useEffect, which runs only on the client.
Conclusion
This solution provides an efficient, scalable, and type-safe way to monitor visible HTML elements on the screen and extract their IDs in real-time. By leveraging React hooks and the IntersectionObserver API, you ensure minimal performance overhead while maintaining clean and maintainable code adhering to best practices.