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

docs: add isLoading and keepPreviousData pages in v2 #343

Merged
merged 25 commits into from
Sep 4, 2022
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
a151bbe
docs: add the Return Values page
koba04 Aug 24, 2022
1a816e0
docs: add isLoading and keepPreviousData option
koba04 Aug 27, 2022
3d31ece
docs: fix header levels
koba04 Aug 27, 2022
59340e6
docs: add a video for keepPreviousData
koba04 Aug 27, 2022
93eef90
docs: move arguments page to next to return values page
koba04 Aug 30, 2022
e2274cc
docs: update diagrams for returning values
koba04 Aug 30, 2022
ef9ee10
docs: update the performance document to add isLoading
koba04 Aug 31, 2022
fc18ba8
docs: keep the list of return values in the options document
koba04 Aug 31, 2022
b2429c5
use isLoading instead of !data
koba04 Aug 31, 2022
da4caf7
translate options.md into Japanese
koba04 Aug 31, 2022
16abf5b
docs: add a detail link for keepPreviousData
koba04 Sep 1, 2022
8c8ba4f
tweak the description of isLoading
koba04 Sep 1, 2022
41f49dc
revert to move the arguments page
koba04 Sep 2, 2022
3509408
move the return values page into the advanced section
koba04 Sep 2, 2022
c363774
rename the Options page to API Options
koba04 Sep 2, 2022
358eccc
fix links to the return values
koba04 Sep 2, 2022
2dd5497
fix a typo
koba04 Sep 2, 2022
7f79c09
add an excalidraw file for the state machine diagrams
koba04 Sep 3, 2022
c5758bf
rename the page from Return Values to Understanding SWR
koba04 Sep 3, 2022
a07951f
rename the Options page to API
koba04 Sep 3, 2022
83f0d81
translate Understanding SWR into Japanese
koba04 Sep 3, 2022
33814f1
tweak
koba04 Sep 3, 2022
5c01f41
change /docs/options links to /docs/api
koba04 Sep 3, 2022
21f0e80
Update pages/docs/advanced/meta.en-US.json
koba04 Sep 4, 2022
2e5b289
change the link of Understanding SWR
koba04 Sep 4, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5,744 changes: 5,744 additions & 0 deletions components/excalidraw/state-machine.excalidraw

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ module.exports = withNextra({
destination: "/docs/advanced/cache",
statusCode: 301,
},
{
source: "/docs/options",
destination: "/docs/api",
statusCode: 301
},
{
source: "/change-log",
destination: "/docs/change-log",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.en-US.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"understanding-swr": "Understanding SWR",
koba04 marked this conversation as resolved.
Show resolved Hide resolved
"cache": "Cache",
"performance": "Performance",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.es-ES.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"understanding-swr": "Understanding SWR",
"cache": "Cache",
"performance": "Rendimiento",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ja.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"understanding-swr": "Understanding SWR",
"cache": "キャッシュ",
"performance": "パフォーマンス",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ko.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"understanding-swr": "Understanding SWR",
"cache": "캐시",
"performance": "성능",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.pt-BR.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"understanding-swr": "Understanding SWR",
"cache": "Cache",
"performance": "Desempenho",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ru.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"understanding-swr": "Understanding SWR",
"cache": "Кеш",
"performance": "Производительность",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.zh-CN.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"understanding-swr": "Understanding SWR",
"cache": "缓存",
"performance": "性能",
"react-native": "React Native",
Expand Down
20 changes: 10 additions & 10 deletions pages/docs/advanced/performance.en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,36 +46,36 @@ Each `<Avatar>` component has a `useSWR` hook inside. Since they have the same S

You can reuse your data hooks (like `useUser` in the example above) everywhere, without worrying about performance or duplicated requests.

There is also a [`dedupingInterval` option](/docs/options) for overriding the default deduplication interval.
There is also a [`dedupingInterval` option](/docs/api) for overriding the default deduplication interval.

## Deep Comparison

SWR **deep compares** data changes by default. If the `data` value isn’t changed, a re-render will not be triggered.

You can also customize the comparison function via the [`compare` option](/docs/options) if you want to change the behavior.
You can also customize the comparison function via the [`compare` option](/docs/api) if you want to change the behavior.
For example, some API responses return a server timestamp that you might want to exclude from the data diff.

## Dependency Collection

`useSWR` returns 3 **stateful** values: `data`, `error` and `isValidating`, each one can be updated independently.
`useSWR` returns 4 **stateful** values: `data`, `error`, `isLoading` and `isValidating`, each one can be updated independently.
For example, if we print those values within a full data-fetching lifecycle, it will be something like this:

```jsx
function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}
```

In the worst case (the first request failed, then the retry was successful), you will see 4 lines of logs:

```js
// console.log(data, error, isValidating)
undefined undefined true // => start fetching
undefined Error false // => end fetching, got an error
undefined Error true // => start retrying
Data undefined false // => end retrying, get the data
// console.log(data, error, isLoading, isValidating)
undefined undefined true true // => start fetching
undefined Error false false // => end fetching, got an error
undefined Error true true // => start retrying
Data undefined false false // => end retrying, get the data
```

The state changes make sense. But that also means our component **rendered 4 times**.
Expand Down
24 changes: 12 additions & 12 deletions pages/docs/advanced/performance.es-ES.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,32 +46,32 @@ function App() {

```

Cada componente `<Avatar/>` tiene un hook `useSWR` en su interior. Dado que tienen el mismo key SWR y
Cada componente `<Avatar/>` tiene un hook `useSWR` en su interior. Dado que tienen el mismo key SWR y
que se renderizan casi al mismo tiempo, **sólo se hará 1 solicitud de red**.

Se pueden reutilizar los hooks de datos (como `useUser` en el ejemplo anterior) en todas partes, sin preocuparse por el rendimiento
o las peticiones duplicadas.

También existe la [opción `dedupingInterval`](/docs/options) para anular el intervalo de deduplicación por defecto.
También existe la [opción `dedupingInterval`](/docs/api) para anular el intervalo de deduplicación por defecto.

## Comparación profunda

SWR por defecto tiene **deep compares** al cambio de datos. Si el valor de `data` no ha cambiado, no se
activará una nueva renderización.

También puede personalizar la función de comparación mediante la [opción `compare`](/docs/options) si quieres cambiar el comportamiento.
También puede personalizar la función de comparación mediante la [opción `compare`](/docs/api) si quieres cambiar el comportamiento.
Por ejemplo, algunas respuestas de la API devuelven una marca de tiempo del servidor que tal vez quiera excluir de la difusión de datos.

## Colección de dependencias

`useSWR` devuelve 3 valores de **estado**: `data`, `error` y `isValidating` cada uno de ellos puede actualizarse de forma independientemente.
`useSWR` devuelve 4 valores de **estado**: `data`, `error`, `isLoading` y `isValidating` cada uno de ellos puede actualizarse de forma independientemente.
Por ejemplo, si imprimimos esos valores dentro de un ciclo de vida completo de obtención de datos, será algo como esto:

```jsx

function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}

Expand All @@ -80,12 +80,12 @@ function App () {
En el peor de los casos (si la primera solicitud falló, entonces el reintento fue exitoso). Se verán 4 líneas de registros:

```js
// console.log(data, error, isValidating)
// console.log(data, error, isLoading, isValidating)

undefined undefined true // => start fetching
undefined Error false // => end fetching, got an error
undefined Error true // => start retrying
Data undefined false // => end retrying, get the data
undefined undefined true true // => start fetching
undefined Error false false // => end fetching, got an error
undefined Error true true // => start retrying
Data undefined false false // => end retrying, get the data
```

Los cambios de estado tienen sentido. Pero eso también significa que nuestro componente se **renderizo 4 veces.**
Expand All @@ -112,7 +112,7 @@ Data // => end retrying, get the data
El mismo proceso ha ocurrido internamente, hubo un error de la primera solicitud, entonces tenemos los datos del reintento.
Sin embargo, **SWR sólo actualiza los estados que utiliza el componente**, que ahora sólo es `data`.

Si no se utilizan siempre estos 3 estados, ya se está beneficiando de esta función. En [Vercel](https://vercel.com), esta optimización se
Si no se utilizan siempre estos 3 estados, ya se está beneficiando de esta función. En [Vercel](https://vercel.com), esta optimización se
traduce en un 60% menos de repeticiones.

## Tree Shaking
Expand Down
20 changes: 10 additions & 10 deletions pages/docs/advanced/performance.ja.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,36 +46,36 @@ function App () {

パフォーマンスや重複したリクエストを心配することなく、どこでも(上記の例にあった `useUser` のように)データフックを再利用できます。

デフォルトの重複排除間隔を上書きする [`dedupingInterval`](/docs/options) オプションもあります。
デフォルトの重複排除間隔を上書きする [`dedupingInterval`](/docs/api) オプションもあります。

## 詳細な比較

SWR は、デフォルトでデータの変更を**詳細に比較**します。`data` という値が変更されていない場合、再レンダリングは開始されません。

動作を変更したい場合は、[`compare` オプション](/docs/options)を使用して比較機能をカスタマイズすることもできます。
動作を変更したい場合は、[`compare` オプション](/docs/api)を使用して比較機能をカスタマイズすることもできます。
たとえば、一部の API レスポンスは、データ差分から除外したいサーバーのタイムスタンプを返します。

## 依存関係のコレクション

`useSWR` が返す三つの**ステートフルな**値、つまり `data` 、`error` 、そして `isValidating` は、それぞれが独立して更新されます。
`useSWR` が返す四つの**ステートフルな**値、つまり `data` 、`error` `isLoading`、そして `isValidating` は、それぞれが独立して更新されます。
たとえば、完全なデータフェッチのライフサイクル内でこれらの値を出力すると次のようになります:

```jsx
function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}
```

最悪の場合(最初のリクエストが失敗し、次に再試行が成功した場合)には、4 行のログが表示されます:

```js
// console.log(data, error, isValidating)
undefined undefined true // => フェッチの開始
undefined Error false // => フェッチの完了、エラーを取得
undefined Error true // => 再試行の開始
Data undefined false // => 再試行の完了、データを取得
// console.log(data, error, isLoading, isValidating)
undefined undefined true true // => フェッチの開始
undefined Error false false // => フェッチの完了、エラーを取得
undefined Error false true // => 再試行の開始
Data undefined false false // => 再試行の完了、データを取得
```

この状態変化は理にかなっています。しかし、それはまた、コンポーネントが **4 回レンダリングされる**ことを意味します。
Expand Down
24 changes: 12 additions & 12 deletions pages/docs/advanced/performance.ko.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

SWR은 모든 종류의 웹 앱에서 중요한 기능들을 제공하므로 **성능**을 가장 중요시합니다.

SWR의 내장 **캐싱**과 **[중복 제거](/advanced/performance#deduplication)** 기능은 불필요한 네트워크 요청을 생략하지만,
SWR의 내장 **캐싱**과 **[중복 제거](/advanced/performance#deduplication)** 기능은 불필요한 네트워크 요청을 생략하지만,
`useSWR` hook 자체의 성능은 여전히 중요합니다. 복잡한 앱에서는 단일 페이지 렌더링에 `useSWR`이 수백 번 호출될 수 있습니다.

SWR은 앱에서 다음을 보장합니다:
Expand All @@ -14,7 +14,7 @@ SWR은 앱에서 다음을 보장합니다:

## 중복 제거

앱에서 SWR hook을 재사용하는 것은 아주 일반적입니다. 예를 들어, 앱이 현재 사용자의 아바타를 다섯 번 렌더링한다면:
앱에서 SWR hook을 재사용하는 것은 아주 일반적입니다. 예를 들어, 앱이 현재 사용자의 아바타를 다섯 번 렌더링한다면:

```jsx
function useUser () {
Expand Down Expand Up @@ -45,36 +45,36 @@ function App () {

성능이나 중복된 요청에 대한 걱정 없이 위 예시의 `useUser`와 같은 데이터 hook을 어디에서든 재사용할 수 있습니다.

기본 중복 제거 인터벌을 오버라이딩할 수 있는 [`dedupingInterval` 옵션](/docs/options)도 있습니다.
기본 중복 제거 인터벌을 오버라이딩할 수 있는 [`dedupingInterval` 옵션](/docs/api)도 있습니다.

## 깊은 비교

SWR은 기본적으로 데이터 변경을 **깊게 비교**합니다. `data` 값이 변경되지 않았다면 리렌더링을 트리거 하지 않습니다.

이 동작을 변경하길 원한다면 [`compare` 옵션](/docs/options)을 통해 비교 함수를 커스터마이징할 수도 있습니다.
이 동작을 변경하길 원한다면 [`compare` 옵션](/docs/api)을 통해 비교 함수를 커스터마이징할 수도 있습니다.
예를 들면, 일부 API의 응답이 데이터 diff에서 제외하길 원하는 서버의 타임 스탬프를 반환합니다.

## 의존성 수집

`useSWR`은 세 개의 **스테이트풀** 값을 반환합니다: `data`, `error`, `isValidating`, 각각은 독립적으로 업데이트됩니다.
`useSWR` returns 4 **stateful** values: `data`, `error`, `isLoading` and `isValidating`, each one can be updated independently.
예를 들어, 전체 데이터 가져오기 생명 주기에서 이 값들을 출력한다면 뭔가 다음과 같은 것입니다.

```jsx
function App () {
const { data, error, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isValidating)
const { data, error, isLoading, isValidating } = useSWR('/api', fetcher)
console.log(data, error, isLoading, isValidating)
return null
}
```

최악의 경우에는(첫 번째 요청이 실패하고, 재시도가 성공), 네 줄의 로그가 보일 것입니다.

```js
// console.log(data, error, isValidating)
undefined undefined true // => 가져오기 시작
undefined Error false // => 가져오기 종료, 에러 발생
undefined Error true // => 재시도 시작
Data undefined false // => 재시도 종료, 데이터 얻음
// console.log(data, error, isLoading, isValidating)
undefined undefined true true // => 가져오기 시작
undefined Error false false // => 가져오기 종료, 에러 발생
undefined Error true true // => 재시도 시작
Data undefined false false // => 재시도 종료, 데이터 얻음
```

상태 변화는 말이 됩니다. 하지만 이는 컴포넌트가 **네 번 리렌더링 되었음**을 의미하기도 합니다.
Expand Down