or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdnative-routing.mdnavigation-hooks.mdreact-router-components.mdreact-router-hooks.mdreact-router-utilities.mdsearch-parameters.md

react-router-hooks.mddocs/

0

# React Router Hooks

1

2

Complete re-export of React Router hooks for accessing navigation state, route data, and programmatic navigation in React Native applications.

3

4

## Capabilities

5

6

### Navigation Hooks

7

8

#### useNavigate

9

10

Returns a navigate function that lets you navigate programmatically, for example in an event handler or an effect.

11

12

```typescript { .api }

13

/**

14

* Returns a function for programmatic navigation

15

* @returns NavigateFunction for programmatic navigation

16

*/

17

function useNavigate(): NavigateFunction;

18

19

interface NavigateFunction {

20

(to: To, options?: NavigateOptions): void;

21

(delta: number): void;

22

}

23

24

interface NavigateOptions {

25

replace?: boolean;

26

state?: any;

27

relative?: RelativeRoutingType;

28

}

29

```

30

31

#### useLocation

32

33

Returns the current location object, which represents the current URL.

34

35

```typescript { .api }

36

/**

37

* Returns the current location object

38

* @returns Location object representing current URL

39

*/

40

function useLocation(): Location;

41

42

interface Location extends Path {

43

state: any;

44

key: string;

45

}

46

47

interface Path {

48

pathname: string;

49

search: string;

50

hash: string;

51

}

52

```

53

54

#### useNavigationType

55

56

Returns the current navigation action which describes how the router came to the current location.

57

58

```typescript { .api }

59

/**

60

* Returns current navigation type

61

* @returns NavigationType indicating how navigation occurred

62

*/

63

function useNavigationType(): NavigationType;

64

65

type NavigationType = "POP" | "PUSH" | "REPLACE";

66

```

67

68

### Route Data Hooks

69

70

#### useParams

71

72

Returns an object of key/value pairs of URL parameters from the current route.

73

74

```typescript { .api }

75

/**

76

* Returns URL parameters from current route

77

* @returns Object containing route parameters

78

*/

79

function useParams(): Params;

80

81

type Params = Record<string, string | undefined>;

82

```

83

84

#### useLoaderData

85

86

Returns the loader data from the current route.

87

88

```typescript { .api }

89

/**

90

* Returns loader data from current route

91

* @returns Data returned by the route's loader function

92

*/

93

function useLoaderData(): unknown;

94

```

95

96

#### useActionData

97

98

Returns the action data from the current route.

99

100

```typescript { .api }

101

/**

102

* Returns action data from current route

103

* @returns Data returned by the route's action function

104

*/

105

function useActionData(): unknown;

106

```

107

108

#### useRouteLoaderData

109

110

Returns the loader data for a specific route by ID.

111

112

```typescript { .api }

113

/**

114

* Returns loader data for specific route

115

* @param routeId - ID of route to get data for

116

* @returns Loader data for specified route

117

*/

118

function useRouteLoaderData(routeId: string): unknown;

119

```

120

121

### Route Matching Hooks

122

123

#### useMatch

124

125

Returns match data about a route at the given path relative to the current location.

126

127

```typescript { .api }

128

/**

129

* Returns match data for a route pattern

130

* @param pattern - Route pattern to match against

131

* @returns PathMatch if pattern matches, null otherwise

132

*/

133

function useMatch(pattern: PathPattern): PathMatch | null;

134

135

interface PathMatch {

136

params: Params;

137

pathname: string;

138

pattern: PathPattern;

139

}

140

141

interface PathPattern {

142

path: string;

143

caseSensitive?: boolean;

144

end?: boolean;

145

}

146

```

147

148

#### useMatches

149

150

Returns the current route matches on the page.

151

152

```typescript { .api }

153

/**

154

* Returns all current route matches

155

* @returns Array of UIMatch objects for current routes

156

*/

157

function useMatches(): UIMatch[];

158

159

interface UIMatch {

160

id: string;

161

pathname: string;

162

params: Params;

163

data: unknown;

164

handle: unknown;

165

}

166

```

167

168

### Utility Hooks

169

170

#### useHref

171

172

Returns a URL href for the given to value that may be used as the value of an `<a href>`.

173

174

```typescript { .api }

175

/**

176

* Returns href string for navigation target

177

* @param to - Navigation target

178

* @param options - Relative routing options

179

* @returns String href for the target

180

*/

181

function useHref(to: To, options?: { relative?: RelativeRoutingType }): string;

182

```

183

184

#### useResolvedPath

185

186

Resolves the pathname of the location in the given to value against the pathname of the current location.

187

188

```typescript { .api }

189

/**

190

* Resolves path relative to current location

191

* @param to - Path to resolve

192

* @param relative - Relative routing type

193

* @returns Resolved Path object

194

*/

195

function useResolvedPath(to: To, relative?: RelativeRoutingType): Path;

196

```

197

198

#### useInRouterContext

199

200

Returns true if the component is a descendant of a `<Router>`.

201

202

```typescript { .api }

203

/**

204

* Checks if component is inside a Router

205

* @returns Boolean indicating router context presence

206

*/

207

function useInRouterContext(): boolean;

208

```

209

210

#### useOutlet

211

212

Returns the element for the child route at this level of the route hierarchy.

213

214

```typescript { .api }

215

/**

216

* Returns child route element

217

* @param context - Context to pass to child routes

218

* @returns React element for child route

219

*/

220

function useOutlet(context?: unknown): React.ReactElement | null;

221

```

222

223

#### useOutletContext

224

225

Returns the context (if provided) for the child route at this level of the route hierarchy.

226

227

```typescript { .api }

228

/**

229

* Returns outlet context from parent route

230

* @returns Context object from parent route

231

*/

232

function useOutletContext<Context = unknown>(): Context;

233

```

234

235

### Advanced Hooks

236

237

#### useBlocker

238

239

Blocks navigation based on a condition. Useful for preventing navigation when there are unsaved changes.

240

241

```typescript { .api }

242

/**

243

* Blocks navigation conditionally

244

* @param shouldBlock - Function or boolean determining if navigation should be blocked

245

* @returns Blocker object with navigation state

246

*/

247

function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;

248

249

interface Blocker {

250

state: "unblocked" | "blocked" | "proceeding";

251

reset(): void;

252

proceed(): void;

253

location?: Location;

254

}

255

256

type BlockerFunction = (args: { currentLocation: Location; nextLocation: Location }) => boolean;

257

```

258

259

#### useNavigation

260

261

Returns the current navigation state: "idle", "loading", or "submitting".

262

263

```typescript { .api }

264

/**

265

* Returns current navigation state

266

* @returns Navigation object with loading states

267

*/

268

function useNavigation(): Navigation;

269

270

interface Navigation {

271

state: "idle" | "loading" | "submitting";

272

location?: Location;

273

formMethod?: string;

274

formAction?: string;

275

formEncType?: string;

276

formData?: FormData;

277

}

278

```

279

280

#### useRevalidator

281

282

Returns a revalidator object for manually revalidating route loaders.

283

284

```typescript { .api }

285

/**

286

* Returns revalidator for manual data revalidation

287

* @returns Revalidator object with revalidate function

288

*/

289

function useRevalidator(): Revalidator;

290

291

interface Revalidator {

292

revalidate(): void;

293

state: "idle" | "loading";

294

}

295

```

296

297

#### Error Handling Hooks

298

299

#### useRouteError

300

301

Returns the error from the current route if there is one.

302

303

```typescript { .api }

304

/**

305

* Returns route error if present

306

* @returns Error object or unknown error

307

*/

308

function useRouteError(): unknown;

309

```

310

311

#### useAsyncError

312

313

Returns any pending async error.

314

315

```typescript { .api }

316

/**

317

* Returns pending async error

318

* @returns Error object or undefined

319

*/

320

function useAsyncError(): unknown;

321

```

322

323

#### useAsyncValue

324

325

Returns the resolved value from the nearest ancestor Await component.

326

327

```typescript { .api }

328

/**

329

* Returns resolved value from ancestor Await

330

* @returns Resolved async value

331

*/

332

function useAsyncValue(): unknown;

333

```

334

335

### Route Definition Hook

336

337

#### useRoutes

338

339

A hook equivalent of the `<Routes>` component for programmatic route definition.

340

341

```typescript { .api }

342

/**

343

* Programmatically define routes

344

* @param routes - Array of route objects

345

* @param locationArg - Optional location override

346

* @returns React element for matching route

347

*/

348

function useRoutes(

349

routes: RouteObject[],

350

locationArg?: Partial<Location> | string

351

): React.ReactElement | null;

352

353

interface RouteObject {

354

path?: string;

355

index?: boolean;

356

children?: React.ReactNode;

357

caseSensitive?: boolean;

358

id?: string;

359

loader?: LoaderFunction;

360

action?: ActionFunction;

361

element?: React.ReactNode | null;

362

Component?: React.ComponentType | null;

363

errorElement?: React.ReactNode | null;

364

ErrorBoundary?: React.ComponentType | null;

365

handle?: RouteHandle;

366

shouldRevalidate?: ShouldRevalidateFunction;

367

lazy?: LazyRouteFunction<RouteObject>;

368

}

369

```

370

371

## Usage Examples

372

373

### Basic Navigation

374

375

```typescript

376

import { useNavigate, useLocation, useParams } from "react-router-native";

377

import { TouchableOpacity, Text, View } from "react-native";

378

379

function ProductDetail() {

380

const navigate = useNavigate();

381

const location = useLocation();

382

const { id } = useParams();

383

384

const goBack = () => {

385

navigate(-1); // Go back one step in history

386

};

387

388

const goToEdit = () => {

389

navigate(`/products/${id}/edit`, {

390

state: { from: location.pathname }

391

});

392

};

393

394

return (

395

<View>

396

<Text>Product ID: {id}</Text>

397

<TouchableOpacity onPress={goBack}>

398

<Text>Back</Text>

399

</TouchableOpacity>

400

<TouchableOpacity onPress={goToEdit}>

401

<Text>Edit Product</Text>

402

</TouchableOpacity>

403

</View>

404

);

405

}

406

```

407

408

### Data Loading

409

410

```typescript

411

import { useLoaderData, useNavigation, useRevalidator } from "react-router-native";

412

413

function ProductList() {

414

const products = useLoaderData() as Product[];

415

const navigation = useNavigation();

416

const revalidator = useRevalidator();

417

418

const isLoading = navigation.state === "loading" || revalidator.state === "loading";

419

420

const refreshData = () => {

421

revalidator.revalidate();

422

};

423

424

return (

425

<View>

426

{isLoading && <Text>Loading...</Text>}

427

{products.map(product => (

428

<View key={product.id}>

429

<Text>{product.name}</Text>

430

</View>

431

))}

432

<TouchableOpacity onPress={refreshData}>

433

<Text>Refresh</Text>

434

</TouchableOpacity>

435

</View>

436

);

437

}

438

```

439

440

### Form Handling with Navigation Blocking

441

442

```typescript

443

import { useBlocker, useNavigate } from "react-router-native";

444

import { useState } from "react";

445

446

function EditForm() {

447

const [formData, setFormData] = useState({ name: "", description: "" });

448

const [isDirty, setIsDirty] = useState(false);

449

const navigate = useNavigate();

450

451

const blocker = useBlocker(

452

({ currentLocation, nextLocation }) =>

453

isDirty && currentLocation.pathname !== nextLocation.pathname

454

);

455

456

const handleSave = () => {

457

// Save logic

458

setIsDirty(false);

459

navigate("/products");

460

};

461

462

const handleCancel = () => {

463

if (isDirty) {

464

// Show confirmation dialog

465

if (confirm("You have unsaved changes. Are you sure?")) {

466

navigate("/products");

467

}

468

} else {

469

navigate("/products");

470

}

471

};

472

473

// Handle blocked navigation

474

if (blocker.state === "blocked") {

475

return (

476

<View>

477

<Text>You have unsaved changes. Are you sure you want to leave?</Text>

478

<TouchableOpacity onPress={blocker.proceed}>

479

<Text>Yes, Leave</Text>

480

</TouchableOpacity>

481

<TouchableOpacity onPress={blocker.reset}>

482

<Text>No, Stay</Text>

483

</TouchableOpacity>

484

</View>

485

);

486

}

487

488

return (

489

<View>

490

{/* Form fields */}

491

<TouchableOpacity onPress={handleSave}>

492

<Text>Save</Text>

493

</TouchableOpacity>

494

<TouchableOpacity onPress={handleCancel}>

495

<Text>Cancel</Text>

496

</TouchableOpacity>

497

</View>

498

);

499

}

500

```

501

502

### Error Handling

503

504

```typescript

505

import { useRouteError } from "react-router-native";

506

import { View, Text } from "react-native";

507

508

function ErrorBoundary() {

509

const error = useRouteError() as Error;

510

511

return (

512

<View>

513

<Text>Something went wrong!</Text>

514

<Text>{error.message}</Text>

515

</View>

516

);

517

}

518

```

519

520

### Programmatic Route Definition

521

522

```typescript

523

import { useRoutes } from "react-router-native";

524

525

function AppRoutes() {

526

const routes = useRoutes([

527

{

528

path: "/",

529

element: <Home />,

530

},

531

{

532

path: "/products",

533

element: <ProductLayout />,

534

children: [

535

{ index: true, element: <ProductList /> },

536

{ path: ":id", element: <ProductDetail /> },

537

{ path: ":id/edit", element: <ProductEdit /> },

538

],

539

},

540

]);

541

542

return routes;

543

}

544

```

545

546

## Types Summary

547

548

```typescript { .api }

549

// Core types

550

type To = string | Partial<Path>;

551

type Params = Record<string, string | undefined>;

552

type RelativeRoutingType = "route" | "path";

553

type NavigationType = "POP" | "PUSH" | "REPLACE";

554

555

// Function types

556

type NavigateFunction = {

557

(to: To, options?: NavigateOptions): void;

558

(delta: number): void;

559

};

560

561

type BlockerFunction = (args: {

562

currentLocation: Location;

563

nextLocation: Location;

564

}) => boolean;

565

566

// Object types

567

interface Location extends Path {

568

state: any;

569

key: string;

570

}

571

572

interface Path {

573

pathname: string;

574

search: string;

575

hash: string;

576

}

577

578

interface NavigateOptions {

579

replace?: boolean;

580

state?: any;

581

relative?: RelativeRoutingType;

582

}

583

584

interface PathMatch {

585

params: Params;

586

pathname: string;

587

pattern: PathPattern;

588

}

589

590

interface PathPattern {

591

path: string;

592

caseSensitive?: boolean;

593

end?: boolean;

594

}

595

```