You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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(newURLSearchParams("?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(newURLSearchParams("?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
+
returnsearchParams;
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