DEV Community

Antoine for Itself Tools

Posted on

Enhancing Accessibility in Next.js with useFocusOnNavigation Custom Hook

At itselftools.com, we've built over 30 web applications using Next.js and Firebase, learning many tricks along the way to improve user experience and application performance. One subtle yet impactful area is accessibility enhancements, particularly in single-page applications (SPAs) like those built with Next.js. Today, we're sharing a custom React hook we've employed to ensure better accessibility across our applications: useFocusOnNavigation.

Understanding the useFocusOnNavigation Hook

The useFocusOnNavigation hook is designed to enhance keyboard navigability by automatically setting the focus to the body element whenever the route changes in a Next.js application. This focus management is crucial for users who rely on keyboard navigation, ensuring they can start interacting with the new page content immediately after navigation occurs.

Here's a breakdown of the code:

import { useEffect } from 'react';
import { useRouter } from 'next/router';

function useFocusOnNavigation() {
  const router = useRouter();
  useEffect(() => {
    const handleRouteChange = () => {
      document.body.tabIndex = '-1';
      document.body.focus();
    };
    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router]);
}

export default useFocusOnNavigation;
Enter fullscreen mode Exit fullscreen mode
  • useEffect and useRouter: These hooks from React and Next.js are used to handle side effects and access the router object, respectively.
  • Event Listener: The hook adds an event listener for routeChangeComplete. When a route change completes, the hook sets the tabIndex of the body to '-1', making it programmatically focusable. Then, it calls document.body.focus() to shift the focus to the body.
  • Cleanup: It also includes a cleanup function to remove the event listener, which helps prevent memory leaks and derogatory performance effects in long-running applications.

This approach is beneficial for maintaining accessibility standards, as automated focus management plays a crucial role in the usability of dynamically loaded content, especially in SPAs.

See It in Action

If you want to experience how our accessibility enhancements influence user interactions in real-world applications, feel free to check out some of our innovative tools:

We hope this hook helps enhance the accessibility of your Next.js applications as much as it has ours, ensuring a smoother and more inclusive user experience.

Top comments (0)