Chuyển đến nội dung

Bài 9 · Expo Router and Navigation

Dynamic Routes and Params

Pass data between screens with Expo Router: dynamic segments, catch-all routes, query parameters, useLocalSearchParams versus useGlobalSearchParams and typing params.

A list screen shows trails; tapping one opens the detail for that trail. The detail screen is one file, but it renders different data depending on a value in the URL. In Expo Router that value is a parameter. There are two kinds: dynamic segments (/trails/42) and query parameters (/trails?sort=length).

The router is read-only here; the live stand-ins reproduce parameter parsing so you can see exactly what values a screen receives.

Dynamic segments

A file or folder in square brackets captures one URL segment:

Text
app/
  trails/
    index.tsx            /trails
    [id].tsx             /trails/42        id = "42"
    [id]/
      reviews.tsx        /trails/42/reviews

Read the value with useLocalSearchParams:

TSX
// app/trails/[id].tsx
import { useLocalSearchParams } from 'expo-router';
import { Text, View } from 'react-native';

export default function TrailDetail() {
  const { id } = useLocalSearchParams<{ id: string }>();
  return (
    <View style={{ padding: 24 }}>
      <Text>Trail id: {id}</Text>
    </View>
  );
}

Params are strings (or arrays of strings). If you need a number, convert and validate: const n = Number(id).

Catch-all segments

[...path].tsx matches one or more segments and gives you an array:

TSX
// app/docs/[...path].tsx   -> /docs/a/b/c
const { path } = useLocalSearchParams<{ path: string[] }>();
// path = ['a', 'b', 'c']

Use it for file-browser style routes, content pages and custom 404 handling inside a section.

TSX
import { Link, router } from 'expo-router';

// as a string
<Link href="/trails/42">Open trail 42</Link>

// as an object (recommended: no string building, and it is type-checked)
<Link href={{ pathname: '/trails/[id]', params: { id: '42', tab: 'photos' } }}>Open</Link>

router.push({ pathname: '/trails/[id]', params: { id: trail.id } });

Parameters that are not part of the path become query parameters: the example above navigates to /trails/42?tab=photos, and the screen reads both id and tab from useLocalSearchParams. Values must be strings, numbers or booleans; do not try to pass objects. Pass an id and load the object in the destination, which also makes the screen work after a deep link or page refresh.

Query parameters

TSX
// opening /trails?sort=length&difficulty=hard
const { sort, difficulty } = useLocalSearchParams<{ sort?: string; difficulty?: string }>();

Change them without leaving the screen by calling router.setParams({ sort: 'rating' }). This is perfect for filters: the state lives in the URL, so it survives reloads and can be shared on web.

JS Extract path and query params

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Building a href from params

The reverse direction is just as useful, and it shows what the router does when you pass params: fill the brackets, send the rest as the query string.

JS Fill a pathname with params

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Local versus global params

Two hooks exist, and the difference matters in stacks and tabs:

  • useLocalSearchParams() returns the params of the route that this screen belongs to, and updates only when that screen's own params change. Use it almost always.
  • useGlobalSearchParams() returns the params of the currently focused route, even if your component is on a screen deeper in the stack that is not focused. A screen buried in the stack would re-render for every change on top of it, which wastes work and can cause surprises.

Use the global hook for things that follow the visible URL (analytics, a header shared across screens).

Validating params

URL values are untrusted: they can come from deep links and the web. Validate them.

TSX
const { id } = useLocalSearchParams<{ id: string }>();
const trailId = Number(id);
if (!Number.isInteger(trailId) || trailId <= 0) {
  return <Redirect href="/+not-found" />;
}

Also handle "valid id but no such record" with an explicit empty state. Typed routes (File-Based Routing) check the pathname at compile time, but never the runtime values.

JS Validate a route param

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Expecting numbers or objects: params are strings. Convert and validate.
  • Passing a whole object as a param. Pass an id and fetch the data in the destination.
  • Using useGlobalSearchParams in a deep screen and re-rendering needlessly.
  • Forgetting to URL-encode values when building strings by hand; prefer the object form of href.
  • Naming a param id in two nested dynamic folders, so one hides the other. Use distinct names ([trailId]/photos/[photoId]).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What type are route params when you read them?

    Params travel in the URL, so they are strings; convert them yourself.
  2. 2. Which file matches /docs/a/b/c and gives you ['a','b','c']?

    A spread segment collects all remaining segments into an array.
  3. 3. In router.push({ pathname: '/trails/[id]', params: { id: '1', tab: 'map' } }), where does tab go?

    Params that do not fill a bracket become query parameters.
  4. 4. When should you prefer useLocalSearchParams over useGlobalSearchParams?

    The local hook is scoped to the screen's route and avoids needless re-renders.

Summary

  • [id] captures one segment, [...path] captures many; read them with useLocalSearchParams.
  • Non-path params become query parameters; router.setParams updates them in place.
  • Params are untrusted strings: validate, and pass ids rather than objects.
  • Use the object form of href for safe, typed navigation.

Next: Links, Redirects and Deep Links

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.