Hooks & Context
Introduction
@esmx/router-react provides hooks and context components for React applications integrated with @esmx/router. This page documents the usage of useRouter(), useRoute(), and RouterProvider.
RouterProvider
- Props:
router: Router— Router instance to providechildren: React.ReactNode— Child components
- Returns:
JSX.Element
Context provider component that makes the router instance available to all descendant components via useRouter() and useRoute().
useRouter()
- Returns:
Router - Throws:
Error— If called outside aRouterProvider
Gets the router instance via React context. Equivalent to useRouter() in @esmx/router-vue.
Usage
useRoute()
- Returns:
Route - Throws:
Error— If called outside aRouterProvider
Gets the current reactive route object. Uses useSyncExternalStore for optimal React integration — the component re-renders automatically when the route changes. Equivalent to useRoute() in @esmx/router-vue.
Usage
Implementation Notes
@esmx/router-react uses React Context to pass the router instance and current route state through the component tree:
RouterProvider— Provides the router instance to descendant components via ContextuseRouter()— Gets the router instance from Context, used for navigationuseRoute()— Gets the current route object from Context, triggers re-render when the route changes
The actual implementation is in the @esmx/router-react package source code and does not need to be implemented manually. The above hooks are included in the package; import and use them directly.