Universal useRouter()
hook
import { useRouter } from '@green-stack/navigation/useRouter'
You can use router.push()
to navigate to a new page:
const router = useRouter()
router.push('/examples/[slug]', '/examples/123')
.push()
will use a push operation on mobile if possible.
There are also other methods available on the router
object:
router.navigate()
- Navigate to the provided hrefrouter.replace()
- Navigate without appending to the historyrouter.back()
- Go back in the historyrouter.canGoBack()
- Check if there’s history that supports invoking theback()
functionrouter.setParams()
- Update the current route query params without navigating
How it works
Each environment has it’s own optimized router. This is why there are also versions specifically for each of those environments:
- useRouter.expo.ts
- useRouter.next.ts
- useRouter.ts
- useRouter.types.ts
Where useRouter.next.ts
covers the Next.js app router, and useRouter.expo.ts
covers Expo Router. The main useRouter.ts
retrieves whichever implementation was provided to the <UniversalAppProviders>
component, which is further passed to <CoreContext.Provider/>
:
ExpoRootLayout.tsx
import { useRouter as useExpoRouter } from '@green-stack/navigation/useRouter.expo'
// ... Later ...
<UniversalAppProviders
useContextRouter={useExpoRouter}
>
...
</UniversalAppProviders>
NextRootLayout.tsx
import { useRouter as useNextRouter } from '@green-stack/navigation/useRouter.next'
// ... Later ...
<UniversalAppProviders
useContextRouter={useNextRouter}
>
...
</UniversalAppProviders>
While the useRouter.types.ts
file ensures both implementations are compatible with the same interface, allowing you to use the same useRouter()
hook across both Expo and Next.js environments.