You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/learn/you-might-not-need-an-effect.md
+30-30Lines changed: 30 additions & 30 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -302,19 +302,19 @@ Questo rimuove l'Effetto inutile e contemporaneamente risolve il bug.
302
302
303
303
### Inviare una richiesta POST {/*sending-a-post-request*/}
304
304
305
-
Questo componente `Form` invia due tipi di richieste POST. It sends an analytics event when it mounts. When you fill in the form and click the Submit button, it will send a POST request to the `/api/register` endpoint:
305
+
Questo componente `Form` invia due tipi di richieste POST. Invia un evento di analytics dopo il mounting. Quando riempi il form e clicchi sul pulsante di Submit, invia una richiesta POST sull'endpoint `/api/register`:
306
306
307
307
```js {5-8,10-16}
308
308
functionForm() {
309
309
const [firstName, setFirstName] =useState('');
310
310
const [lastName, setLastName] =useState('');
311
311
312
-
// ✅ Good: This logic should run because the component was displayed
312
+
// ✅ Buono: Questa logica funzionerà perché il componente è stato già mostrato
Let's apply the same criteria as in the example before.
333
+
Applichiamo lo stesso criterio dell'esempio precedente.
334
334
335
-
The analytics POST request should remain in an Effect. This is because the _reason_ to send the analytics event is that the form was displayed. (It would fire twice in development, but [see here](/learn/synchronizing-with-effects#sending-analytics) for how to deal with that.)
335
+
la richiesta POST di analytics dovrebbe rimanere in un Effetto. Questo perché il _motivo_ per inviare un evento di analytics è che il form viene mostrato. (Dovrebbe eseguire due volte in modalità di sviluppo, [leggi qui](/learn/synchronizing-with-effects#sending-analytics) per capire come gestirlo.)
336
336
337
-
However, the `/api/register`POST request is not caused by the form being _displayed_. You only want to send the request at one specific moment in time: when the user presses the button. It should only ever happen _on that particular interaction_. Delete the second Effect and move that POST request into the event handler:
337
+
Comunque, la richiesta POST `/api/register`non è causata dal fatto che il Form viene _mostrato_. Vuoi soltanto inviare la richiesta in un momento specifico nel tempo: quando l'utente preme il pulsante. Dovrebbe succedere _solo in quella interazione specifica_. Elimina il secondo Effetto e sposta la richiesta POST nell'event handler:
338
338
339
339
```js {12-13}
340
340
functionForm() {
341
341
const [firstName, setFirstName] =useState('');
342
342
const [lastName, setLastName] =useState('');
343
343
344
-
// ✅ Good: This logic runs because the component was displayed
344
+
// ✅ Buono: Questa logica funziona perché l'evento è stato mostrato
// ✅ Good: Event-specific logic is in the event handler
351
+
// ✅ Buona: La logica specifica dell'evento è nel suo event handler
352
352
post('/api/register', { firstName, lastName });
353
353
}
354
354
// ...
355
355
}
356
356
```
357
357
358
-
When you choose whether to put some logic into an event handler or an Effect, the main question you need to answer is _what kind of logic_ it is from the user's perspective. If this logic is caused by a particular interaction, keep it in the event handler. If it's caused by the user _seeing_ the component on the screen, keep it in the Effect.
358
+
Quando devi scegliere se inserire della logica in un event handler o in un Effetto, la domanda principale a cui devi rispondere è _che tipo di logica_ è dal punto di vista dell'utente. Se è logica causata da una interazione particolare, mantienila nel suo event handler. Se è causata dal fatto che l'utente sta _vedendo_ il componente sullo schermo, mantienila nell'Effetto.
359
359
360
-
### Chains of computations {/*chains-of-computations*/}
360
+
### Catena di computazione {/*chains-of-computations*/}
361
361
362
-
Sometimes you might feel tempted to chain Effects that each adjust a piece of state based on other state:
362
+
A volte puoi essere tentato di concatenare Effetti che modificano un pezzo di state basandosi su altro state:
// 🔴 Avoid: Chains of Effects that adjust the state solely to trigger each other
371
+
// 🔴 Evita: Catene di Effetti che modificano lo stato soltanto per scatenare altri Effetti
372
372
useEffect(() => {
373
373
if (card !==null&&card.gold) {
374
374
setGoldCardCount(c=> c +1);
@@ -403,29 +403,29 @@ function Game() {
403
403
// ...
404
404
```
405
405
406
-
There are two problems with this code.
406
+
Ci sono due problemi con questo codice:
407
407
408
-
One problem is that it is very inefficient: the component (and its children) have to re-render between each `set`call in the chain. In the example above, in the worst case (`setCard` → render → `setGoldCardCount` → render → `setRound` → render → `setIsGameOver` → render) there are three unnecessary re-renders of the tree below.
408
+
Un problema è che è molto inefficiente: il componente (e i suoi figli) devono re-renderizzare tra ogni chiamata `set`nella catena. Nell'esempio su, nel caso peggiore (`setCard` → render → `setGoldCardCount` → render → `setRound` → render → `setIsGameOver` → render) ci sono tre re-renders non necessari dell'albero sottostante.
409
409
410
-
Even if it weren't slow, as your code evolves, you will run into cases where the "chain" you wrote doesn't fit the new requirements. Imagine you are adding a way to step through the history of the game moves. You'd do it by updating each state variable to a value from the past. However, setting the `card`state to a value from the past would trigger the Effect chain again and change the data you're showing. Such code is often rigid and fragile.
410
+
Anche se non è lento, con l'evolversi del codice, andrai incontro a casi in cui la "catena" che hai scritto non soddisfa i requisiti. Immagina che stai aggiungendo un modo per muoverti attraverso lo storico dei movimenti di un gioco. Lo faresti aggiornando ogni variabile di state dal passato. Tuttavia, impostare lo state `card`da un valore passato azionerebbe la catena dell'Effetto nuovamente e cambierebbe i dati che stai mostrando. Il codice così è rigido e fragile.
411
411
412
-
In this case, it's better to calculate what you can during rendering, and adjust the state in the event handler:
412
+
In questo caso, è meglio calcolare ciò che puoi durante il rendering, e regolare lo state nell'event handler:
// ✅ Calculate all the next state in the event handler
428
+
// ✅ Calcola il prossimo state nell'event handler
429
429
setCard(nextCard);
430
430
if (nextCard.gold) {
431
431
if (goldCardCount <=3) {
@@ -443,21 +443,21 @@ function Game() {
443
443
// ...
444
444
```
445
445
446
-
This is a lot more efficient. Also, if you implement a way to view game history, now you will be able to set each state variable to a move from the past without triggering the Effect chain that adjusts every other value. If you need to reuse logic between several event handlers, you can [extract a function](#sharing-logic-between-event-handlers) and call it from those handlers.
446
+
Questo è molto più efficiente. Inoltre, se implementi un modo per vedere lo storico della partita, ora sei capace di muovere ogni variabile di state nel passato senza azionare la catena dovuta all'Effetto che regola ogni altro valore. Se necessiti di riutilizzare logica tra diversi event handlers, puoi [estrarre una funzione](#sharing-logic-between-event-handlers) e chiamarla al loro interno.
447
447
448
-
Remember that inside event handlers, [state behaves like a snapshot.](/learn/state-as-a-snapshot) For example, even after you call`setRound(round +1)`, the `round`variable will reflect the value at the time the user clicked the button. If you need to use the next value for calculations, define it manually like`constnextRound= round +1`.
448
+
Ricorda che negli event handlers, [lo state si comporta come un'istantanea.](/learn/state-as-a-snapshot) Per esempio, anche dopo aver chiamato`setRound(round +1)`, la variabile di state `round`corrisponderà al valore che aveva quando l' utente ha cliccato sul pulsante. Se hai bisogno del prossimo valore per effettuare calcoli, definiscilo manualmente in modo simile a questo:`constnextRound= round +1`.
449
449
450
-
In some cases, you *can't* calculate the next state directly in the event handler. For example, imagine a form with multiple dropdowns where the options of the next dropdown depend on the selected value of the previous dropdown. Then, a chain of Effects is appropriate because you are synchronizing with network.
450
+
In alcuni casi, *non puoi* calcolare il prossimo stato direttamente nell'event handler. Per esempio, immagina un form con dropdowns multiple in cui la option della prossima dropdown dipende dal valore selezionato in quella precedente. In questo caso, una catena di Effetti è appropriata perché stai sincronizzando lo state con la rete.
451
451
452
-
### Initializing the application {/*initializing-the-application*/}
Some logic should only run once when the app loads.
454
+
Alcune logiche dovrebbero partire solo una volta dopo che l'app viene caricata.
455
455
456
-
You might be tempted to place it in an Effect in the top-level component:
456
+
Potresti essere tentato di inserirla in un Effetto al componente di primo livello:
457
457
458
458
```js {2-6}
459
459
functionApp() {
460
-
// 🔴 Avoid: Effects with logic that should only ever run once
460
+
// 🔴 Evita: Effetti con logica che dovrebbe eseguire una volta sola
461
461
useEffect(() => {
462
462
loadDataFromLocalStorage();
463
463
checkAuthToken();
@@ -466,9 +466,9 @@ function App() {
466
466
}
467
467
```
468
468
469
-
However, you'll quickly discover that it [runs twice in development.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) This can cause issues--for example, maybe it invalidates the authentication token because the function wasn't designed to be called twice. In general, your components should be resilient to being remounted. This includes your top-level `App` component.
469
+
Tuttavia, scoprirai presto che [gira due volte in modalità di sviluppo.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) Questo può causare problemi--per esempio, potrebbe invalidare il token di autenticazione perché la funzione non era stata progettata per essere chiamata due volte. In generale, i tuoi componenti dovrebbero essere resilienti quando vengono rimontati. Includendo il componente di primo livello `App`.
470
470
471
-
Although it may not ever get remounted in practice in production, following the same constraints in all components makes it easier to move and reuse code. If some logic must run *once per app load* rather than *once per component mount*, add a top-level variable to track whether it has already executed:
471
+
Anche se in produzione potrebbe non essere smontato mai, seguire gli stessi vincoli in tutti i componenti rende più facile muovere e riutilizzare codice. Se della logica deve eseguire *una volta per caricamento dell'app* invece che *una volta ogni volta che il componente viene montato*, aggiungi una variabile al primo livello per tracciarne l'esecuzione:
472
472
473
473
```js {1,5-6,10}
474
474
let didInit =false;
@@ -477,7 +477,7 @@ function App() {
477
477
useEffect(() => {
478
478
if (!didInit) {
479
479
didInit =true;
480
-
// ✅ Only runs once per app load
480
+
// ✅ Esegue una volta quando l'app carica
481
481
loadDataFromLocalStorage();
482
482
checkAuthToken();
483
483
}
@@ -486,11 +486,11 @@ function App() {
486
486
}
487
487
```
488
488
489
-
You can also run it during module initialization and before the app renders:
489
+
Puoi anche eseguirlo durante l'inizializzazione del modulo e prima della renderizzazione dell'app:
490
490
491
491
```js {1,5}
492
492
if (typeofwindow!=='undefined') { // Check if we're running in the browser.
0 commit comments