Skip to content

Hooks FAQ #145

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

Closed
wants to merge 3 commits into from
Closed
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
64 changes: 32 additions & 32 deletions content/docs/hooks-faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -528,9 +528,9 @@ Jeżeli nie jesteś zaznajomiony z tą składnią, sprawdź [wyjaśnienie](/docs

Tak. Zapoznaj się z [warunkowym uruchamianiem efektów](/docs/hooks-reference.html#conditionally-firing-an-effect). Pamiętaj jednak, że pomijanie aktualizacji często [prowadzi do błędów](/docs/hooks-effect.html#explanation-why-effects-run-on-each-update), z tego też powodu nie jest to domyślnie działanie.

### Is it safe to omit functions from the list of dependencies? {#is-it-safe-to-omit-functions-from-the-list-of-dependencies}
### Czy bezpiecznie jest pomijać funkcje w liście zależności? {#is-it-safe-to-omit-functions-from-the-list-of-dependencies}

Generally speaking, no.
Ogólnie rzecz biorąc, nie.

```js{3,8}
function Example({ someProp }) {
Expand All @@ -540,11 +540,11 @@ function Example({ someProp }) {

useEffect(() => {
doSomething();
}, []); // 🔴 This is not safe (it calls `doSomething` which uses `someProp`)
}, []); // 🔴 Niebezpieczne (wywołuje `doSomething`, które używa `someProp`)
}
```

It's difficult to remember which props or state are used by functions outside of the effect. This is why **usually you'll want to declare functions needed by an effect *inside* of it.** Then it's easy to see what values from the component scope that effect depends on:
Trudno jest pamiętać, które właściwości lub stan są używane przez funkcje poza efektem. Dlatego też **zazwyczaj lepiej jest deklarować funkcje *wewnątrz* efektu.** Dzięki temu łatwo można zauważyć, od których wartości komponentu zależy efekt:

```js{4,8}
function Example({ someProp }) {
Expand All @@ -554,72 +554,72 @@ function Example({ someProp }) {
}

doSomething();
}, [someProp]); // ✅ OK (our effect only uses `someProp`)
}, [someProp]); // ✅ OK (efekt używa wyłącznie `someProp`)
}
```

If after that we still don't use any values from the component scope, it's safe to specify `[]`:
Jeżeli po zmianach efekt nadal nie używa wartości z zakresu komponentu, można bezpiecznie użyć `[]`:

```js{7}
useEffect(() => {
function doSomething() {
console.log('hello');
console.log('witaj');
}

doSomething();
}, []); // ✅ OK in this example because we don't use *any* values from component scope
}, []); // ✅ OK, ponieważ *żadne* wartości z zakresu komponentu nie są używane wewnątrz efektu
```

Depending on your use case, there are a few more options described below.
W zależności od przypadku użycia, istnieje kilka dodatkowych opcji, które opisaliśmy poniżej.

>Note
>Uwaga
>
>We provide the [`exhaustive-deps`](https://github.com/facebook/react/issues/14920) ESLint rule as a part of the [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks#installation) package. It helps you find components that don't handle updates consistently.
>Stworzyliśmy regułę [`exhaustive-deps`](https://github.com/facebook/react/issues/14920) (pol. *wyczerpujące zależności*), będącą częścią pakietu [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks#installation). Pomaga w znalezieniu komponentów, które nie obsługują aktualizacji w konsekwentny sposób.

Let's see why this matters.
Spójrzmy, dlaczego ma to znaczenie.

If you specify a [list of dependencies](/docs/hooks-reference.html#conditionally-firing-an-effect) as the last argument to `useEffect`, `useMemo`, `useCallback`, or `useImperativeHandle`, it must include all values used inside that participate in the React data flow. That includes props, state, and anything derived from them.
Kiedy określasz [tablicę zależności](/docs/hooks-reference.html#conditionally-firing-an-effect), ostatni argument dla `useEffect`, `useMemo`, `useCallback`, lub `useImperativeHandle` powinien zawierać wszystkie wartości biorące udział w przepływie danych Reacta. Włączając w to właściwości, stan i wszystkie ich pochodne.

It is **only** safe to omit a function from the dependency list if nothing in it (or the functions called by it) references props, state, or values derived from them. This example has a bug:
Jedynym **bezpiecznym** przypadkiem pominięcia argumentu w tablicy zależności jest przekazanie funkcji, która w swoim wnętrzu nie ma odniesień do właściwości, stanu lub wartości z nich dziedziczących. Poniższy przykład zawiera błąd:

```js{5,12}
function ProductPage({ productId }) {
const [product, setProduct] = useState(null);

async function fetchProduct() {
const response = await fetch('http://myapi/product' + productId); // Uses productId prop
const response = await fetch('http://myapi/product' + productId); // Używa właściwości productId
const json = await response.json();
setProduct(json);
}

useEffect(() => {
fetchProduct();
}, []); // 🔴 Invalid because `fetchProduct` uses `productId`
}, []); // 🔴 Błąd, ponieważ `fetchProduct` używa `productId`
// ...
}
```

**The recommended fix is to move that function _inside_ of your effect**. That makes it easy to see which props or state your effect uses, and to ensure they're all declared:
**Zalecanym sposobem naprawienia tego, jest przeniesienie funkcji do _wnętrzna_ efektu**. Dzięki temu łatwo możemy dostrzec stan lub właściwości, których używa efekt i upewnić się, że wszystkie z nich zostały zadeklarowane:

```js{5-10,13}
function ProductPage({ productId }) {
const [product, setProduct] = useState(null);

useEffect(() => {
// By moving this function inside the effect, we can clearly see the values it uses.
// Po przeniesienu funkcji do wnętrza efektu, możemy łatwo dostrzec, których wartości używa.
async function fetchProduct() {
const response = await fetch('http://myapi/product' + productId);
const json = await response.json();
setProduct(json);
}

fetchProduct();
}, [productId]); // ✅ Valid because our effect only uses productId
}, [productId]); // ✅ Poprawnie, ponieważ efekt używa wyłącznie productId
// ...
}
```

This also allows you to handle out-of-order responses with a local variable inside the effect:
Pozwala to również na obsłużenie asynchronicznych odpowiedzi stosując zmienną lokalną wewnątrz efektu:

```js{2,6,10}
useEffect(() => {
Expand All @@ -635,37 +635,37 @@ This also allows you to handle out-of-order responses with a local variable insi
}, [productId]);
```

We moved the function inside the effect so it doesn't need to be in its dependency list.
Przenieśliśmy funkcję do wnętrza efektu, dlatego też nie musi się znajdować w tablicy zależności.

>Tip
>Wskazówka
>
>Check out [this small demo](https://codesandbox.io/s/jvvkoo8pq3) and [this article](https://www.robinwieruch.de/react-hooks-fetch-data/) to learn more about data fetching with Hooks.
>Aby dowiedzieć się więcej o pobieraniu danych za pomocą hooków, sprawdź [ten przykład](https://codesandbox.io/s/jvvkoo8pq3) i [ten artykuł](https://www.robinwieruch.de/react-hooks-fetch-data/).

**If for some reason you _can't_ move a function inside an effect, there are a few more options:**
**Jeżeli z jakichś przyczyn _nie_ możesz przenieść funkcji do wnętrza efektu, istnieje kilka innych opcji:**

* **You can try moving that function outside of your component**. In that case, the function is guaranteed to not reference any props or state, and also doesn't need to be in the list of dependencies.
* If the function you're calling is a pure computation and is safe to call while rendering, you may **call it outside of the effect instead,** and make the effect depend on the returned value.
* As a last resort, you can **add a function to effect dependencies but _wrap its definition_** into the [`useCallback`](/docs/hooks-reference.html#usecallback) Hook. This ensures it doesn't change on every render unless *its own* dependencies also change:
* **Możesz spróbować przenieść funkcję poza swój komponent**. W tym przypadku, funkcja nie będzie odnosić się do żadnych właściwości czy stanu, dlatego też nie będzie potrzeby dodawania jej do tablicy zależności.
* Jeżeli funkcja, którą wywołujesz, wykonuje jedynie obliczenia i można ją bezpiecznie wywołać podczas renderowania, możesz zechcieć **wywołać ją poza efektem ** i uzależnić efekt od zwróconej przez nią wartości.
* W ostateczności, możesz **dodać funkcję do zależności efektu poprzez _opakowanie jej definicji_**, korzystając z hooka [`useCallback`](/docs/hooks-reference.html#usecallback). Zapewnia to niezmienność podczas renderowania, dopóki nie zmieni się również *jej własna* tablica zależności:

```js{2-5}
function ProductPage({ productId }) {
// ✅ Wrap with useCallback to avoid change on every render
// ✅ Opakowanie za pomocą useCallback, aby uniknąć zmian przy każdym renderowaniu
const fetchProduct = useCallback(() => {
// ... Does something with productId ...
}, [productId]); // ✅ All useCallback dependencies are specified
// ... Korzysta z productId ...
}, [productId]); // ✅ Zdefiniowane zostały wszystkie zależności useCallback

return <ProductDetails fetchProduct={fetchProduct} />;
}

function ProductDetails({ fetchProduct }) {
useEffect(() => {
fetchProduct();
}, [fetchProduct]); // ✅ All useEffect dependencies are specified
}, [fetchProduct]); // ✅ Zdefiniowane zostały wszystkie zależności useEffect
// ...
}
```

Note that in the above example we **need** to keep the function in the dependencies list. This ensures that a change in the `productId` prop of `ProductPage` automatically triggers a refetch in the `ProductDetails` component.
Zauważ, że w powyższym przykładzie **musieliśmy** przekazać funkcję do tablicy zależności. Dzięki temu zmiana właściwości `productId` w `ProductPage` będzie automatycznie uruchamiała ponowne pobranie danych w komponencie `ProductDetails`.

### What can I do if my effect dependencies change too often? {#what-can-i-do-if-my-effect-dependencies-change-too-often}

Expand Down