Skip to content

Feature(hooks-rules): Italian translation #180

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

Merged
merged 2 commits into from
Sep 13, 2019
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
108 changes: 54 additions & 54 deletions content/docs/hooks-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,133 +6,133 @@ next: hooks-custom.html
prev: hooks-effect.html
---

*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class.
Gli *Hooks* sono stati aggiunti in React 16.8. Ti permettono di utilizzare `state` ed altre funzioni di React senza dover scrivere una classe.

Hooks are JavaScript functions, but you need to follow two rules when using them. We provide a [linter plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) to enforce these rules automatically:
Gli Hooks sono funzioni JavaScript, ma devi seguire due regole quando li utilizzi. Forniamo un [plugin linter](https://www.npmjs.com/package/eslint-plugin-react-hooks) per imporre queste regole automaticamente.

### Only Call Hooks at the Top Level {#only-call-hooks-at-the-top-level}
### Chiama gli Hooks solo al livello più alto {#only-call-hooks-at-the-top-level}

**Don't call Hooks inside loops, conditions, or nested functions.** Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple `useState` and `useEffect` calls. (If you're curious, we'll explain this in depth [below](#explanation).)
**Non chiamare gli Hooks all'interno di cicli, condizioni, o funzioni annidate.** Invece, utilizza sempre gli Hooks al livello più alto della tua funzione React. Seguendo questa regola, ti assicuri che gli Hooks siano chiamati nello stesso ordine ogni volta che un componente viene renderizzato. Questo è ciò che permette a React di mantenere correttamente lo stato degli Hooks tra più chiamate `useState` e `useEffect`. (Se sei curioso, lo spiegheremo in profondità [qui](#explanation).)

### Only Call Hooks from React Functions {#only-call-hooks-from-react-functions}
### Chiama gli Hooks solo da Funzioni React {#only-call-hooks-from-react-functions}

**Don't call Hooks from regular JavaScript functions.** Instead, you can:
**Non chiamare gli Hooks da funzioni JavaScript normali.** Invece, puoi:

* ✅ Call Hooks from React function components.
* ✅ Call Hooks from custom Hooks (we'll learn about them [on the next page](/docs/hooks-custom.html)).
* ✅ Chiamare gli Hooks da componenti funzione React.
* ✅ Chiamare gli Hooks dagli Hooks personalizzati (che vedremo [nella pagina successiva](/docs/hooks-custom.html)).

By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
Seguendo questa regola, ti assicuri che tutta la logica con stato in un componente sia chiaramente visibile dal suo codice sorgente.

## ESLint Plugin {#eslint-plugin}
## Plugin ESLint {#eslint-plugin}

We released an ESLint plugin called [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) that enforces these two rules. You can add this plugin to your project if you'd like to try it:
Abbiamo rilasciato un plugin ESLint chiamato [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) che impone queste due regole. Puoi aggiungere questo plugin al tuo progetto, qualora volessi provarlo:

```bash
npm install eslint-plugin-react-hooks --save-dev
```

```js
// Your ESLint configuration
// La tua configurazione ESLint
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
"react-hooks/rules-of-hooks": "error", // Checks rules of Hooks
"react-hooks/exhaustive-deps": "warn" // Checks effect dependencies
"react-hooks/rules-of-hooks": "error", // Controlla le regole degli Hooks
"react-hooks/exhaustive-deps": "warn" // Controlla le dipendenze dell'effect
}
}
```

In the future, we intend to include this plugin by default into Create React App and similar toolkits.
In futuro, abbiamo intenzione di includere di default questo plugin dentro Create React App e toolkit simili.

**You can skip to the next page explaining how to write [your own Hooks](/docs/hooks-custom.html) now.** On this page, we'll continue by explaining the reasoning behind these rules.
**Puoi passare alla pagina successiva che spiega come scrivere [i tuoi Hooks](/docs/hooks-custom.html) adesso.** In questa pagina, continueremo spiegando il ragionamento alla base di queste regole.

## Explanation {#explanation}
## Spiegazione {#explanation}

As we [learned earlier](/docs/hooks-state.html#tip-using-multiple-state-variables), we can use multiple State or Effect Hooks in a single component:
Come abbiamo [appreso prima](/docs/hooks-state.html#tip-using-multiple-state-variables), possiamo utilizzare più Hook State o Hook Effect all'interno di un singolo componente:

```js
function Form() {
// 1. Use the name state variable
const [name, setName] = useState('Mary');
// 1. Usa la variabile di stato nome
const [nome, setNome] = useState('Mary');

// 2. Use an effect for persisting the form
// 2. Usa un effect per la persistenza del form
useEffect(function persistForm() {
localStorage.setItem('formData', name);
localStorage.setItem('formData', nome);
});

// 3. Use the surname state variable
const [surname, setSurname] = useState('Poppins');
// 3. Usa la variabile di stato cognome
const [cognome, setCognome] = useState('Poppins');

// 4. Use an effect for updating the title
// 4. Usa un effect per aggiornare il title
useEffect(function updateTitle() {
document.title = name + ' ' + surname;
document.title = nome + ' ' + cognome;
});

// ...
}
```

So how does React know which state corresponds to which `useState` call? The answer is that **React relies on the order in which Hooks are called**. Our example works because the order of the Hook calls is the same on every render:
Quindi come fa React a sapere quale stato corrisponde a ogni chiamata a `useState`? La risposta è che **React si basa sull'ordine in cui vengono chiamati gli Hooks**. Il nostro esempio funziona perché l'ordine delle chiamate agli Hooks è lo stesso in ogni render:

```js
// ------------
// First render
// Primo render
// ------------
useState('Mary') // 1. Initialize the name state variable with 'Mary'
useEffect(persistForm) // 2. Add an effect for persisting the form
useState('Poppins') // 3. Initialize the surname state variable with 'Poppins'
useEffect(updateTitle) // 4. Add an effect for updating the title
useState('Mary') // 1. Inizializza la variabile di stato nome con 'Mary'
useEffect(persistForm) // 2. Aggiungi un effetto per persistere il form
useState('Poppins') // 3. Inizializza la variabile di stato cognome con 'Poppins'
useEffect(updateTitle) // 4. Aggiunge un effetto per aggiornare il title

// -------------
// Second render
// Secondo render
// -------------
useState('Mary') // 1. Read the name state variable (argument is ignored)
useEffect(persistForm) // 2. Replace the effect for persisting the form
useState('Poppins') // 3. Read the surname state variable (argument is ignored)
useEffect(updateTitle) // 4. Replace the effect for updating the title
useState('Mary') // 1. Leggi la variabile di stato nome (l'argomento è ignorato)
useEffect(persistForm) // 2. Sostituisce l'effect per persistere il form
useState('Poppins') // 3. Leggi la variabile di stato cognome (l'argomento è ignorato)
useEffect(updateTitle) // 4. Sostituisce l'effect per aggiornare il title

// ...
```

As long as the order of the Hook calls is the same between renders, React can associate some local state with each of them. But what happens if we put a Hook call (for example, the `persistForm` effect) inside a condition?
Finché l'ordine delle chiamate agli Hooks è lo stesso tra un render e l'altro, React è in grado di associare uno stato locale a ciascuno di essi. Ma cosa succede se inseriamo una chiamata ad un Hook (ad esempio, all'effect `persistForm`) dentro una condizione?

```js
// 🔴 We're breaking the first rule by using a Hook in a condition
if (name !== '') {
// 🔴 Stiamo infrangendo la prima regola utilizzando un Hook in una condizione
if (nome !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', name);
localStorage.setItem('formData', nome);
});
}
```

The `name !== ''` condition is `true` on the first render, so we run this Hook. However, on the next render the user might clear the form, making the condition `false`. Now that we skip this Hook during rendering, the order of the Hook calls becomes different:
La condizione `nome !== ''` è `true` nel primo render, quindi eseguiamo questo Hook. Tuttavia, al render successivo l'utente potrebbe cancellare il form, rendendo la condizione `false`. Ora che saltiamo questo Hook durante il render, l'ordine delle chiamate agli Hook risulta diverso:

```js
useState('Mary') // 1. Read the name state variable (argument is ignored)
// useEffect(persistForm) // 🔴 This Hook was skipped!
useState('Poppins') // 🔴 2 (but was 3). Fail to read the surname state variable
useEffect(updateTitle) // 🔴 3 (but was 4). Fail to replace the effect
useState('Mary') // 1. Leggi la variabile di stato nome (l'argomento è ignorato)
// useEffect(persistForm) // 🔴 Questo Hook è stato saltato!
useState('Poppins') // 🔴 2 (ma era 3). Impossibile leggere la variabile di stato cognome
useEffect(updateTitle) // 🔴 3 (ma era 4). Impossibile sostituire l'effect per aggiornare il title
```

React wouldn't know what to return for the second `useState` Hook call. React expected that the second Hook call in this component corresponds to the `persistForm` effect, just like during the previous render, but it doesn't anymore. From that point, every next Hook call after the one we skipped would also shift by one, leading to bugs.
React non saprebbe cosa restituire per la seconda chiamata all'Hook `useState`. React si aspettava che la seconda chiamata all'Hook in questo componente corrispondesse all'effect `persistForm`, esattamente come nel render precedente, ma non è più così. Da quel punto in poi, anche ogni successiva chiamata ad un Hook dopo quella che è stata saltata risulterebbe traslata di uno, introducendo dei bug.

**This is why Hooks must be called on the top level of our components.** If we want to run an effect conditionally, we can put that condition *inside* our Hook:
**Ecco perché gli Hooks devono essere chiamati dal livello più alto dei nostri componenti.** Se vogliamo eseguire un effect in maniera condizionata, possiamo mettere la condizione *dentro* il nostro Hook:

```js
useEffect(function persistForm() {
// 👍 We're not breaking the first rule anymore
if (name !== '') {
localStorage.setItem('formData', name);
// 👍 Non stiamo più infrangendo la prima regola
if (nome !== '') {
localStorage.setItem('formData', nome);
}
});
```

**Note that you don't need to worry about this problem if you use the [provided lint rule](https://www.npmjs.com/package/eslint-plugin-react-hooks).** But now you also know *why* Hooks work this way, and which issues the rule is preventing.
**Nota che non devi preoccuparti di questo problema se utilizzi la [regola del linter](https://www.npmjs.com/package/eslint-plugin-react-hooks) descritta in predecenza.** Ma ora sai anche *perché* gli Hooks funzionano così, e quali problemi questa regola previene.

## Next Steps {#next-steps}
## Prossimi passi {#next-steps}

Finally, we're ready to learn about [writing your own Hooks](/docs/hooks-custom.html)! Custom Hooks let you combine Hooks provided by React into your own abstractions, and reuse common stateful logic between different components.
Finalmente, siamo pronti per imparare a [scrivere i tuoi Hooks](/docs/hooks-custom.html)! Gli Hooks personalizzati ti permettono di utilizzare gli Hooks forniti da React all'interno delle tue astrazioni, e riutilizzare la logica di stato comune tra componenti diversi.