or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

hooks.mdindex.mdlocation-strategies.mdrouting-components.md

hooks.mddocs/

0

# Hooks

1

2

Programmatic hooks for accessing and controlling routing state, including location management, route matching, parameter extraction, and router configuration access.

3

4

## Capabilities

5

6

### useLocation Hook

7

8

Returns the current location and a navigation function, providing the primary interface for location-aware components and navigation logic.

9

10

```typescript { .api }

11

/**

12

* Hook for accessing current location and navigation function

13

* @returns Tuple of [currentPath, navigateFunction]

14

*/

15

function useLocation<H extends BaseLocationHook = BrowserLocationHook>(): HookReturnValue<H>;

16

17

type HookReturnValue<H extends BaseLocationHook> = ReturnType<H>;

18

```

19

20

**Usage Examples:**

21

22

```typescript

23

import { useLocation } from "wouter";

24

25

function MyComponent() {

26

const [location, navigate] = useLocation();

27

28

// Current path

29

console.log(location); // "/users/123"

30

31

// Navigate programmatically

32

const handleClick = () => {

33

navigate("/dashboard");

34

};

35

36

// Navigate with options

37

const handleReplace = () => {

38

navigate("/settings", { replace: true });

39

};

40

41

return (

42

<div>

43

<p>Current location: {location}</p>

44

<button onClick={handleClick}>Go to Dashboard</button>

45

<button onClick={handleReplace}>Replace with Settings</button>

46

</div>

47

);

48

}

49

```

50

51

### useRoute Hook

52

53

Matches a route pattern against the current location and extracts parameters, useful for conditional rendering and parameter access outside of Route components.

54

55

```typescript { .api }

56

/**

57

* Hook for matching route patterns and extracting parameters

58

* @param pattern - Route pattern to match (string with :param syntax or RegExp)

59

* @returns Match result tuple - [isMatch, params] or [false, null]

60

*/

61

function useRoute<T extends DefaultParams | undefined = undefined, RoutePath extends PathPattern = PathPattern>(

62

pattern: RoutePath

63

): Match<T extends DefaultParams ? T : RoutePath extends string ? StringRouteParams<RoutePath> : RegexRouteParams>;

64

65

type Match<T extends DefaultParams = DefaultParams> =

66

| [true, Params<T>]

67

| [false, null];

68

```

69

70

**Usage Examples:**

71

72

```typescript

73

import { useRoute } from "wouter";

74

75

function UserProfile() {

76

const [match, params] = useRoute("/users/:id");

77

78

if (!match) {

79

return <div>Not on user profile page</div>;

80

}

81

82

return (

83

<div>

84

<h1>User Profile</h1>

85

<p>User ID: {params.id}</p>

86

</div>

87

);

88

}

89

90

function ConditionalNav() {

91

const [isOnDashboard] = useRoute("/dashboard");

92

const [isOnSettings] = useRoute("/settings");

93

94

return (

95

<nav className={isOnDashboard ? "dashboard-nav" : "default-nav"}>

96

{isOnSettings && <SettingsMenu />}

97

</nav>

98

);

99

}

100

```

101

102

### useRouter Hook

103

104

Provides access to the current router configuration and context, useful for accessing routing options and creating custom navigation logic.

105

106

```typescript { .api }

107

/**

108

* Hook for accessing current router context and configuration

109

* @returns RouterObject with current routing configuration

110

*/

111

function useRouter(): RouterObject;

112

113

interface RouterObject {

114

/** Current location hook being used */

115

readonly hook: BaseLocationHook;

116

/** Current search hook for query parameters */

117

readonly searchHook: BaseSearchHook;

118

/** Base path for all routes */

119

readonly base: Path;

120

/** Own base path (without inherited base) */

121

readonly ownBase: Path;

122

/** Route pattern parser function */

123

readonly parser: Parser;

124

/** Static SSR path if configured */

125

readonly ssrPath?: Path;

126

/** Static SSR search string if configured */

127

readonly ssrSearch?: SearchString;

128

/** HREF formatting function */

129

readonly hrefs: HrefsFormatter;

130

}

131

```

132

133

**Usage Examples:**

134

135

```typescript

136

import { useRouter } from "wouter";

137

138

function RouterInfo() {

139

const router = useRouter();

140

141

return (

142

<div>

143

<p>Base path: {router.base}</p>

144

<p>Using SSR: {router.ssrPath ? "Yes" : "No"}</p>

145

</div>

146

);

147

}

148

149

function CustomNavigation() {

150

const router = useRouter();

151

const [location, navigate] = router.hook(router);

152

153

const handleNavigate = (path: string) => {

154

// Custom navigation logic with base path

155

const fullPath = router.base + path;

156

navigate(fullPath);

157

};

158

159

return (

160

<button onClick={() => handleNavigate("/custom")}>

161

Custom Navigate

162

</button>

163

);

164

}

165

```

166

167

### useParams Hook

168

169

Accesses route parameters from the nearest Route component context, providing a convenient way to get matched parameters in nested components.

170

171

```typescript { .api }

172

/**

173

* Hook for accessing route parameters from nearest Route context

174

* @returns Object containing matched route parameters

175

*/

176

function useParams<T = undefined>(): T extends string

177

? StringRouteParams<T>

178

: T extends undefined

179

? DefaultParams

180

: T;

181

182

interface DefaultParams {

183

readonly [paramName: string | number]: string | undefined;

184

}

185

```

186

187

**Usage Examples:**

188

189

```typescript

190

import { useParams } from "wouter";

191

192

// Inside a Route with path="/users/:id/posts/:postId"

193

function PostDetail() {

194

const params = useParams();

195

196

return (

197

<div>

198

<h1>Post {params.postId}</h1>

199

<p>By user {params.id}</p>

200

</div>

201

);

202

}

203

204

// With type safety

205

function TypedPostDetail() {

206

const params = useParams<"/users/:userId/posts/:postId">();

207

208

// params.userId and params.postId are typed

209

return (

210

<div>

211

<h1>Post {params.postId}</h1>

212

<p>By user {params.userId}</p>

213

</div>

214

);

215

}

216

```

217

218

### useSearch Hook

219

220

Accesses the current URL search/query string, providing access to query parameters separately from the main location path.

221

222

```typescript { .api }

223

/**

224

* Hook for accessing URL search/query parameters

225

* @returns Current search string (without leading ?)

226

*/

227

function useSearch<H extends BaseSearchHook = BrowserSearchHook>(): ReturnType<H>;

228

229

type BaseSearchHook = (...args: any[]) => SearchString;

230

type BrowserSearchHook = (options?: { ssrSearch?: SearchString }) => SearchString;

231

```

232

233

**Usage Examples:**

234

235

```typescript

236

import { useSearch } from "wouter";

237

238

function SearchExample() {

239

const search = useSearch();

240

241

// Parse search manually

242

const params = new URLSearchParams(search);

243

const query = params.get("q");

244

const page = params.get("page");

245

246

return (

247

<div>

248

<p>Search query: {query}</p>

249

<p>Current page: {page}</p>

250

<p>Full search: {search}</p>

251

</div>

252

);

253

}

254

```

255

256

### useSearchParams Hook

257

258

Provides managed access to URL search parameters with a setter function, similar to React's useState but for URL search parameters.

259

260

```typescript { .api }

261

/**

262

* Hook for managing URL search parameters with getter and setter

263

* @returns Tuple of [URLSearchParams, setSearchParams function]

264

*/

265

function useSearchParams(): [URLSearchParams, SetSearchParams];

266

267

type SetSearchParams = (

268

nextInit: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit),

269

options?: { replace?: boolean; state?: any }

270

) => void;

271

272

type URLSearchParamsInit = ConstructorParameters<typeof URLSearchParams>[0];

273

```

274

275

**Usage Examples:**

276

277

```typescript

278

import { useSearchParams } from "wouter";

279

280

function SearchForm() {

281

const [searchParams, setSearchParams] = useSearchParams();

282

283

const currentQuery = searchParams.get("q") || "";

284

const currentPage = parseInt(searchParams.get("page") || "1");

285

286

const handleSearch = (query: string) => {

287

setSearchParams({ q: query, page: "1" });

288

};

289

290

const handlePageChange = (page: number) => {

291

setSearchParams(prev => {

292

const newParams = new URLSearchParams(prev);

293

newParams.set("page", page.toString());

294

return newParams;

295

});

296

};

297

298

return (

299

<div>

300

<input

301

value={currentQuery}

302

onChange={(e) => handleSearch(e.target.value)}

303

placeholder="Search..."

304

/>

305

<p>Page: {currentPage}</p>

306

<button onClick={() => handlePageChange(currentPage + 1)}>

307

Next Page

308

</button>

309

</div>

310

);

311

}

312

313

function FilterControls() {

314

const [searchParams, setSearchParams] = useSearchParams();

315

316

const setFilter = (key: string, value: string) => {

317

setSearchParams(

318

prev => {

319

const newParams = new URLSearchParams(prev);

320

newParams.set(key, value);

321

return newParams;

322

},

323

{ replace: true } // Don't add to history

324

);

325

};

326

327

return (

328

<div>

329

<select onChange={(e) => setFilter("category", e.target.value)}>

330

<option value="">All Categories</option>

331

<option value="tech">Technology</option>

332

<option value="design">Design</option>

333

</select>

334

</div>

335

);

336

}

337

```

338

339

## Utility Function

340

341

### matchRoute Function

342

343

Low-level function for manually matching route patterns against paths, useful for custom routing logic and testing.

344

345

```typescript { .api }

346

/**

347

* Manually match a route pattern against a path

348

* @param parser - Route pattern parser function

349

* @param pattern - Route pattern to match

350

* @param path - Path to match against

351

* @param loose - Enable loose matching for nested routes

352

* @returns Match result tuple - [isMatch, params, base?]

353

*/

354

function matchRoute<T extends DefaultParams | undefined = undefined, RoutePath extends PathPattern = PathPattern>(

355

parser: Parser,

356

pattern: RoutePath,

357

path: string,

358

loose?: boolean

359

): Match<T extends DefaultParams ? T : RoutePath extends string ? StringRouteParams<RoutePath> : RegexRouteParams>;

360

```

361

362

**Usage Examples:**

363

364

```typescript

365

import { matchRoute, useRouter } from "wouter";

366

367

function CustomMatcher() {

368

const { parser } = useRouter();

369

370

// Manual route matching

371

const [matches, params] = matchRoute(parser, "/users/:id", "/users/123");

372

373

if (matches) {

374

console.log("User ID:", params.id); // "123"

375

}

376

377

// Loose matching for nested routes

378

const [nestedMatch, nestedParams, base] = matchRoute(

379

parser,

380

"/admin/:section",

381

"/admin/users/list",

382

true

383

);

384

385

if (nestedMatch) {

386

console.log("Section:", nestedParams.section); // "users"

387

console.log("Base:", base); // "/admin/users"

388

}

389

390

return <div>Custom matching logic</div>;

391

}

392

```

393

394

## Types

395

396

```typescript { .api }

397

type StringRouteParams<T extends string> = RouteParams<T> & {

398

[param: number]: string | undefined;

399

};

400

401

type RegexRouteParams = {

402

[key: string | number]: string | undefined

403

};

404

405

type Params<T extends DefaultParams = DefaultParams> = T;

406

407

type HookNavigationOptions<H extends BaseLocationHook> =

408

EmptyInterfaceWhenAnyOrNever<

409

NonNullable<Parameters<HookReturnValue<H>[1]>[1]>

410

>;

411

```