
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
React Portability Patterns
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/>
:
import { useRouter as useExpoRouter } from '@green-stack/navigation/useRouter.expo'
// ... Later ...
const expoContextRouter = useExpoRouter()
<UniversalAppProviders
contextRouter={expoContextRouter}
>
...
</UniversalAppProviders>
import { useRouter as useNextRouter } from '@green-stack/navigation/useRouter.next'
// ... Later ...
const nextContextRouter = useNextRouter()
<UniversalAppProviders
contextRouter={nextContextRouter}
>
...
</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.
Why this pattern?
The ‘React Portability Patterns’ used here are designed to ensure that you can easily reuse optimized versions of hooks across different flavours of writing React.
On the one hand, that means it’s already set up to work with both Expo and Next.js in an optimal way.
But, you can actually add your own implementations for other environments, without having to refactor the code that uses the useRouter
hook.
Supporting more environments
Just add your own useRouter.<environment>.ts
file that respects the shared types, and then pass it to the <UniversalAppProviders>
component as contextRouter
.