Skip to content

Commit

Permalink
docs: add isLoading and keepPreviousData pages in v2 (#343)
Browse files Browse the repository at this point in the history
* docs: add the Return Values page

* docs: add isLoading and keepPreviousData option

* docs: fix header levels

* docs: add a video for keepPreviousData

* docs: move arguments page to next to return values page

* docs: update diagrams for returning values

* docs: update the performance document to add isLoading

* docs: keep the list of return values in the options document

* use isLoading instead of !data

* translate options.md into Japanese

* docs: add a detail link for keepPreviousData

* tweak the description of isLoading

* revert to move the arguments page

* move the return values page into the advanced section

* rename the Options page to API Options

* fix links to the return values

* fix a typo

* add an excalidraw file for the state machine diagrams

* rename the page from Return Values to Understanding SWR

* rename the Options page to API

* translate Understanding SWR into Japanese

* tweak

* change /docs/options links to /docs/api

* Update pages/docs/advanced/meta.en-US.json

Co-authored-by: Jiachi Liu <inbox@huozhi.im>

* change the link of Understanding SWR

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
  • Loading branch information
koba04 and huozhi committed Sep 4, 2022
1 parent 602e161 commit 5567dd5
Show file tree
Hide file tree
Showing 83 changed files with 7,507 additions and 1,031 deletions.
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
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
@@ -1,4 +1,5 @@
{
"understanding": "Understanding SWR",
"cache": "Cache",
"performance": "Performance",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.es-ES.json
@@ -1,4 +1,5 @@
{
"understanding": "Understanding SWR",
"cache": "Cache",
"performance": "Rendimiento",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ja.json
@@ -1,4 +1,5 @@
{
"understanding": "Understanding SWR",
"cache": "キャッシュ",
"performance": "パフォーマンス",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ko.json
@@ -1,4 +1,5 @@
{
"understanding": "Understanding SWR",
"cache": "캐시",
"performance": "성능",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.pt-BR.json
@@ -1,4 +1,5 @@
{
"understanding": "Understanding SWR",
"cache": "Cache",
"performance": "Desempenho",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.ru.json
@@ -1,4 +1,5 @@
{
"understanding": "Understanding SWR",
"cache": "Кеш",
"performance": "Производительность",
"react-native": "React Native",
Expand Down
1 change: 1 addition & 0 deletions pages/docs/advanced/meta.zh-CN.json
@@ -1,4 +1,5 @@
{
"understanding": "Understanding SWR",
"cache": "缓存",
"performance": "性能",
"react-native": "React Native",
Expand Down
20 changes: 10 additions & 10 deletions pages/docs/advanced/performance.en-US.mdx
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
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
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
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

0 comments on commit 5567dd5

Please sign in to comment.