Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

02-app > 02-api-reference > 04-functions > use-search-params #417

Merged
merged 7 commits into from
Jul 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 61 additions & 63 deletions docs/02-app/02-api-reference/04-functions/use-search-params.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
---
title: useSearchParams
description: API Reference for the useSearchParams hook.
description: useSearchParams hook에 대한 API 레퍼런스입니다.
---

`useSearchParams` is a **Client Component** hook that lets you read the current URL's **query string**.
`useSearchParams`는 현재 URL의 **쿼리 문자열**을 읽을 수 있는 **클라이언트 컴포넌트** hook입니다.

`useSearchParams` returns a **read-only** version of the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) interface.
`useSearchParams`는 **읽기 전용** 버전의 [`URLSearchParams`](https://developer.mozilla.org/ko/docs/Web/API/URLSearchParams) 인터페이스를 반환합니다.

```tsx filename="app/dashboard/search-bar.tsx" switcher
'use client'
Expand Down Expand Up @@ -39,50 +39,50 @@ export default function SearchBar() {
}
```

## Parameters
## 매개변수

```tsx
const searchParams = useSearchParams()
```

`useSearchParams` does not take any parameters.
`useSearchParams` 어떠한 매개변수도 받지 않습니다.

## Returns
## 반환값

`useSearchParams` returns a **read-only** version of the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) interface, which includes utility methods for reading the URL's query string:
`useSearchParams`는 URL의 쿼리 문자열을 읽기 위한 유틸리티 메서드를 포함하는 **읽기 전용** 버전의 [`URLSearchParams`](https://developer.mozilla.org/ko/docs/Web/API/URLSearchParams) 인터페이스를 반환합니다.

- [`URLSearchParams.get()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get): Returns the first value associated with the search parameter. For example:
- [`URLSearchParams.get()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get): 검색 매개변수의 첫 번째 값을 반환합니다. 예를 들어

| URL | `searchParams.get("a")` |
| -------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `/dashboard?a=1` | `'1'` |
| `/dashboard?a=` | `''` |
| `/dashboard?b=3` | `null` |
| `/dashboard?a=1&a=2` | `'1'` _- use [`getAll()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/getAll) to get all values_ |
| URL | `searchParams.get("a")` |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `/dashboard?a=1` | `'1'` |
| `/dashboard?a=` | `''` |
| `/dashboard?b=3` | `null` |
| `/dashboard?a=1&a=2` | `'1'` - 모든 값을 얻으려면 [`getAll()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/getAll) 을 사용하세요. |

- [`URLSearchParams.has()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/has): Returns a boolean value indicating if the given parameter exists. For example:
- [`URLSearchParams.has()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/has): 주어진 매개변수가 존재하는지 여부를 나타내는 boolean 값을 반환합니다. 예를 들면

| URL | `searchParams.has("a")` |
| ---------------- | ----------------------- |
| `/dashboard?a=1` | `true` |
| `/dashboard?b=3` | `false` |

- Learn more about other **read-only** methods of [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams), including the [`getAll()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/getAll), [`keys()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/keys), [`values()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/values), [`entries()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/entries), [`forEach()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/forEach), and [`toString()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/toString).
- [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)의 다른 **읽기 전용** 메서드에 대해 자세히 알아보기, [`getAll()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/getAll), [`keys()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/keys), [`values()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/values), [`entries()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/entries), [`forEach()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/forEach), [`toString()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/toString).

> **Good to know**:
> **참고**:
>
> - `useSearchParams` is a [Client Component](/docs/getting-started/react-essentials) hook and is **not supported** in [Server Components](/docs/getting-started/react-essentials) to prevent stale values during [partial rendering](/docs/app/building-your-application/routing#partial-rendering).
> - If an application includes the `/pages` directory, `useSearchParams` will return `ReadonlyURLSearchParams | null`. The `null` value is for compatibility during migration since search params cannot be known during pre-rendering of a page that doesn't use `getServerSideProps`
> - `useSearchParams`는 [클라이언트 컴포넌트](/docs/getting-started/react-essentials) hook으로 [부분 렌더링](/docs/app/building-your-application/routing#partial-rendering) 중 오래된 값을 방지하기 위해 [서버 컴포넌트](/docs/getting-started/react-essentials)에서는 **지원하지 않습니다**.
> - 애플리케이션에 `/pages` 디렉토리가 포함된 경우, `useSearchParams``ReadonlyURLSearchParams | null`을 반환합니다. `null` 값은 마이그레이션 중 호환성을 위한 것으로, `getServerSideProps`를 사용하지 않는 페이지의 사전 렌더링 중에는 검색 매개변수를 알 수 없기 때문입니다.

## Behavior
## 동작

### Static Rendering
### 정적 렌더링

If a route is [statically rendered](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default), calling `useSearchParams()` will cause the tree up to the closest [`Suspense` boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming#example) to be client-side rendered.
경로가 [정적으로 렌더링](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#static-rendering-default)되는 경우, useSearchParams()를 호출하면 가장 가까운 [Suspense 경계](/docs/app/building-your-application/routing/loading-ui-and-streaming#example)까지의 트리가 클라이언트 측에서 렌더링 됩니다.

This allows a part of the page to be statically rendered while the dynamic part that uses `searchParams` is client-side rendered.
이렇게 하면 `searchParams`를 사용하는 동적인 부분이 클라이언트 측에서 렌더링 되는 동안 페이지의 일부가 정적으로 렌더링 됩니다.

You can reduce the portion of the route that is client-side rendered by wrapping the component that uses `useSearchParams` in a `Suspense` boundary. For example:
`useSearchParams`를 사용하는 컴포넌트를 `Suspense` 경계로 감싸서 클라이언트 측에서 렌더링되는 경로의 일부를 줄일 수 있습니다. 예를 들어

```tsx filename="app/dashboard/search-bar.tsx" switcher
'use client'
Expand All @@ -94,7 +94,7 @@ export default function SearchBar() {

const search = searchParams.get('search')

// This will not be logged on the server when using static rendering
// 정적 렌더링을 사용할 때는 서버에 기록하지 않습니다.
console.log(search)

return <>Search: {search}</>
Expand All @@ -111,7 +111,7 @@ export default function SearchBar() {

const search = searchParams.get('search')

// This will not be logged on the server when using static rendering
// 정적 렌더링을 사용할 때는 서버에 기록하지 않습니다.
console.log(search)

return <>Search: {search}</>
Expand All @@ -122,10 +122,10 @@ export default function SearchBar() {
import { Suspense } from 'react'
import SearchBar from './search-bar'

// This component passed as a fallback to the Suspense boundary
// will be rendered in place of the search bar in the initial HTML.
// When the value is available during React hydration the fallback
// will be replaced with the `<SearchBar>` component.
// 서스펜스 경계에 폴백으로 전달된 이 컴포넌트는
// 초기 HTML의 검색창 대신 렌더링됩니다.
// 리액트 하이드레이션 중에 값을 사용할 수 있는 경우, 폴백은
// `<SearchBar>` 컴포넌트로 대체합니다.
function SearchBarFallback() {
return <>placeholder</>
}
Expand All @@ -148,10 +148,10 @@ export default function Page() {
import { Suspense } from 'react'
import SearchBar from './search-bar'

// This component passed as a fallback to the Suspense boundary
// will be rendered in place of the search bar in the initial HTML.
// When the value is available during React hydration the fallback
// will be replaced with the `<SearchBar>` component.
// 서스펜스 경계에 폴백으로 전달된 이 컴포넌트는
// 초기 HTML의 검색창 대신 렌더링됩니다.
// 리액트 하이드레이션 중에 값을 사용할 수 있는 경우, 폴백은
// `<SearchBar>` 컴포넌트로 대체합니다.
function SearchBarFallback() {
return <>placeholder</>
}
Expand All @@ -170,13 +170,13 @@ export default function Page() {
}
```

### Dynamic Rendering
### 동적 렌더링

If a route is [dynamically rendered](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering), `useSearchParams` will be available on the server during the initial server render of the Client Component.
경로가 [동적으로 렌더링](/docs/app/building-your-application/rendering/static-and-dynamic-rendering#dynamic-rendering) 되는 경우, 클라이언트 컴포넌트의 초기 서버 렌더링 중에 서버에서 `useSearchParams`를 사용할 수 있습니다.

> **Good to know**: Setting the [`dynamic` route segment config option](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) to `force-dynamic` can be used to force dynamic rendering.
> **참조**: [`동적` 경로 세그먼트 구성 옵션](/docs/app/api-reference/file-conventions/route-segment-config#dynamic)`force-dynamic`으로 설정하면 동적 렌더링을 강제할 수 있습니다.

For example:
예를 들어

```tsx filename="app/dashboard/search-bar.tsx" switcher
'use client'
Expand All @@ -188,8 +188,8 @@ export default function SearchBar() {

const search = searchParams.get('search')

// This will be logged on the server during the initial render
// and on the client on subsequent navigations.
// 초기 렌더링 중에는 서버에,
// 이후 탐색 시에는 클라이언트에 기록합니다.
console.log(search)

return <>Search: {search}</>
Expand All @@ -206,8 +206,8 @@ export default function SearchBar() {

const search = searchParams.get('search')

// This will be logged on the server during the initial render
// and on the client on subsequent navigations.
// 초기 렌더링 중에는 서버에,
// 이후 탐색 시에는 클라이언트에 기록합니다.
console.log(search)

return <>Search: {search}</>
Expand Down Expand Up @@ -248,32 +248,31 @@ export default function Page() {
}
```

### Server Components
### 서버 컴포넌트

#### Pages
#### 페이지

To access search params in [Pages](/docs/app/api-reference/file-conventions/page) (Server Components), use the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop.
[페이지](/docs/app/api-reference/file-conventions/page)(서버 컴포넌트)에서 검색 매개변수에 접근하려면 [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop을 사용합니다.

#### Layouts
#### 레이아웃

Unlike Pages, [Layouts](/docs/app/api-reference/file-conventions/layout) (Server Components) **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/building-your-application/routing#partial-rendering) which could lead to stale `searchParams` between navigations. View [detailed explanation](/docs/app/api-reference/file-conventions/layout#layouts-do-not-receive-searchparams).
페이지와 달리 [레이아웃](/docs/app/api-reference/file-conventions/layout)(서버 컴포넌트)은 `searchParams` prop을 **받지 않습니다.** 이는 공유된 레이아웃이 [탐색 중에는 다시 렌더링 되지 않아](/docs/app/building-your-application/routing#partial-rendering) `searchParams`이 오래될 수 있기 때문입니다. [자세한 설명](/docs/app/api-reference/file-conventions/layout#layouts-do-not-receive-searchparams)을 확인하세요.

Instead, use the Page [`searchParams`](/docs/app/api-reference/file-conventions/page) prop or the [`useSearchParams`](/docs/app/api-reference/functions/use-params) hook in a Client Component, which is re-rendered on the client with the latest `searchParams`.
대신 클라이언트 컴포넌트에서 페이지 [`searchParams`](/docs/app/api-reference/file-conventions/page) prop 또는 [`useSearchParams`](/docs/app/api-reference/functions/use-params) hook을 사용하면 클라이언트에서 최신 `searchParams`를 사용하여 다시 렌더링 됩니다.

## Examples
## 예시

### Updating `searchParams`
### `searchParams` 업데이트

You can use [`useRouter`](/docs/app/api-reference/functions/use-router) or [`Link`](/docs/app/api-reference/components/link) to set new `searchParams`. After a navigation is performed, the current [`page.js`](/docs/app/api-reference/file-conventions/page) will receive an updated [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional).
[`useRouter`](/docs/app/api-reference/functions/use-router) 또는 [`Link`](/docs/app/api-reference/components/link)를 사용하여 새 `searchParams`를 설정할 수 있습니다. 탐색 후 현재 `page.js`는 업데이트된 [`searchParams` prop](/docs/app/api-reference/file-conventions/page#searchparams-optional)를 받게 됩니다.

```tsx filename="app/example-client-component.tsx" switcher
export default function ExampleClientComponent() {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()!

// Get a new searchParams string by merging the current
// searchParams with a provided key/value pair
// 현재 searchParams를 키/값 쌍과 병합하여 새 searchParams 문자열을 가져옵니다.
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams)
Expand All @@ -288,7 +287,7 @@ export default function ExampleClientComponent() {
<>
<p>Sort By</p>

{/* using useRouter */}
{/* useRouter 사용*/}
<button
onClick={() => {
// <pathname>?sort=asc
Expand All @@ -298,7 +297,7 @@ export default function ExampleClientComponent() {
ASC
</button>

{/* using <Link> */}
{/* <Link> 사용*/}
<Link
href={
// <pathname>?sort=desc
Expand All @@ -318,8 +317,7 @@ export default function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()

// Get a new searchParams string by merging the current
// searchParams with a provided key/value pair
// 현재 searchParams를 키/값 쌍과 병합하여 새 searchParams 문자열을 가져옵니다.
const createQueryString = useCallback(
(name, value) => {
const params = new URLSearchParams(searchParams)
Expand All @@ -334,7 +332,7 @@ export default function ExampleClientComponent() {
<>
<p>Sort By</p>

{/* using useRouter */}
{/* useRouter 사용*/}
<button
onClick={() => {
// <pathname>?sort=asc
Expand All @@ -344,7 +342,7 @@ export default function ExampleClientComponent() {
ASC
</button>

{/* using <Link> */}
{/* <Link> 사용*/}
<Link
href={
// <pathname>?sort=desc
Expand All @@ -358,8 +356,8 @@ export default function ExampleClientComponent() {
}
```

## Version History
## 버전 히스토리

| Version | Changes |
| --------- | ----------------------------- |
| `v13.0.0` | `useSearchParams` introduced. |
| 버전 | 변경사항 |
| --------- | ----------------------- |
| `v13.0.0` | `useSearchParams` 도입. |