Skip to content

Commit 0fe8731

Browse files
committed
added some search params documentation
1 parent be5e97d commit 0fe8731

File tree

1 file changed

+62
-1
lines changed

1 file changed

+62
-1
lines changed

docs/api/hooks/useSearchParams.md

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,65 @@ useSearchParams(defaultInit): undefined
3333

3434
[modes: framework, data, declarative]
3535

36-
_No documentation_
36+
You can initialize the search params with a default value, though it **will not** change the URL on the first render.
37+
38+
```tsx
39+
// a search param string
40+
useSearchParams("?tab=1");
41+
42+
// a short-hand object
43+
useSearchParams({ tab: "1" });
44+
45+
// object keys can be arrays for multiple values on the key
46+
useSearchParams({ brand: ["nike", "reebok"] });
47+
48+
// an array of tuples
49+
useSearchParams([["tab", "1"]]);
50+
51+
// a URLSearchParams object
52+
useSearchParams(new URLSearchParams("?tab=1"));
53+
```
54+
55+
## SetSearchParams Function
56+
57+
The second element of the tuple is a function that can be used to update the search params. It accepts the same types as `defaultInit` and will cause a navigation to the new URL.
58+
59+
```tsx
60+
let [searchParams, setSearchParams] = useSearchParams();
61+
62+
// a search param string
63+
setSearchParams("?tab=1");
64+
65+
// a short-hand object
66+
setSearchParams({ tab: "1" });
67+
68+
// object keys can be arrays for multiple values on the key
69+
setSearchParams({ brand: ["nike", "reebok"] });
70+
71+
// an array of tuples
72+
setSearchParams([["tab", "1"]]);
73+
74+
// a URLSearchParams object
75+
setSearchParams(new URLSearchParams("?tab=1"));
76+
```
77+
78+
It also supports a function callback like `setState`:
79+
80+
```tsx
81+
setSearchParams((searchParams) => {
82+
searchParams.set("tab", "2");
83+
return searchParams;
84+
});
85+
```
86+
87+
## Notes
88+
89+
Note that `searchParams` is a stable reference, so you can reliably use it as a dependency in `useEffect` hooks.
90+
91+
```tsx
92+
useEffect(() => {
93+
console.log(searchParams.get("tab"));
94+
}, [searchParams]);
95+
```
96+
97+
However, this also means it's mutable. If you change the object without calling `setSearchParams`, its values will change between renders if some other state causes the component to re-render and URL will not reflect the values.

0 commit comments

Comments
 (0)