diff --git a/src/content/reference/react/useEffect.md b/src/content/reference/react/useEffect.md
index 218e65ffb..6bc71d024 100644
--- a/src/content/reference/react/useEffect.md
+++ b/src/content/reference/react/useEffect.md
@@ -1,10 +1,17 @@
---
title: useEffect
+translationStatus: ai-draft
---
+
+
+Questa pagina è stata tradotta automaticamente e supervisionata da un maintainer. Un'ulteriore revisione da parte della community sarebbe comunque utile. [Migliora questa traduzione](https://github.com/reactjs/it.react.dev/edit/main/src/content/reference/react/useEffect.md).
+
+
+
-`useEffect` is a React Hook that lets you [synchronize a component with an external system.](/learn/synchronizing-with-effects)
+`useEffect` è un Hook React che ti permette di [sincronizzare un componente con un sistema esterno.](/learn/synchronizing-with-effects)
```js
useEffect(setup, dependencies?)
@@ -20,7 +27,7 @@ useEffect(setup, dependencies?)
### `useEffect(setup, dependencies?)` {/*useeffect*/}
-Call `useEffect` at the top level of your component to declare an Effect:
+Chiama `useEffect` al top level del tuo componente per dichiarare un Effetto:
```js
import { useState, useEffect } from 'react';
@@ -40,45 +47,45 @@ function ChatRoom({ roomId }) {
}
```
-[See more examples below.](#usage)
+[Vedi altri esempi sotto.](#usage)
#### Parameters {/*parameters*/}
-* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. When your [component commits](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom), React will run your setup function. After every commit with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function.
+* `setup`: La funzione con la logica del tuo Effetto. La funzione di setup può anche restituire opzionalmente una funzione di *cleanup*. Quando il tuo [componente esegue la fase di commit](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom), React eseguirà la funzione di setup. Dopo ogni fase di commit con dipendenze cambiate, React eseguirà prima la funzione di cleanup (se l'hai fornita) con i valori precedenti, e poi eseguirà la funzione di setup con i nuovi valori. Dopo che il componente viene rimosso dal DOM, React eseguirà la funzione di cleanup.
-* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. If you omit this argument, your Effect will re-run after every commit of the component. [See the difference between passing an array of dependencies, an empty array, and no dependencies at all.](#examples-dependencies)
+* **optional** `dependencies`: L'elenco di tutti i valori reattivi referenziati all'interno del codice di `setup`. I valori reattivi includono props, state e tutte le variabili e funzioni dichiarate direttamente nel corpo del componente. Se il tuo linter è [configurato per React](/learn/editor-setup#linting), verificherà che ogni valore reattivo sia specificato correttamente come dipendenza. L'elenco delle dipendenze deve avere un numero costante di elementi ed essere scritto inline come `[dep1, dep2, dep3]`. React confronterà ogni dipendenza con il suo valore precedente usando il confronto [`Object.is`](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Se ometti questo argomento, il tuo Effetto verrà rieseguito dopo ogni fase di commit del componente. [Vedi la differenza tra passare un array di dipendenze, un array vuoto e nessuna dipendenza.](#examples-dependencies)
#### Returns {/*returns*/}
-`useEffect` returns `undefined`.
+`useEffect` restituisce `undefined`.
#### Caveats {/*caveats*/}
-* `useEffect` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
+* `useEffect` è un Hook, quindi puoi chiamarlo **solo al top level del tuo componente** o dei tuoi Hook. Non puoi chiamarlo all'interno di loop o condizioni. Se ne hai bisogno, estrai un nuovo componente e sposta lo state al suo interno.
-* If you're **not trying to synchronize with some external system,** [you probably don't need an Effect.](/learn/you-might-not-need-an-effect)
+* Se **non stai cercando di sincronizzarti con un sistema esterno,** [probabilmente non ti serve un Effetto.](/learn/you-might-not-need-an-effect)
-* When Strict Mode is on, React will **run one extra development-only setup+cleanup cycle** before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, [implement the cleanup function.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
+* Quando Strict Mode è attivo, React **eseguirà un ciclo setup+cleanup extra solo in development** prima del primo setup reale. È un test di stress che verifica che la logica di cleanup "specchi" la logica di setup e che fermi o annulli ciò che fa il setup. Se questo causa un problema, [implementa la funzione di cleanup.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
-* If some of your dependencies are objects or functions defined inside the component, there is a risk that they will **cause the Effect to re-run more often than needed.** To fix this, remove unnecessary [object](#removing-unnecessary-object-dependencies) and [function](#removing-unnecessary-function-dependencies) dependencies. You can also [extract state updates](#updating-state-based-on-previous-state-from-an-effect) and [non-reactive logic](#reading-the-latest-props-and-state-from-an-effect) outside of your Effect.
+* Se alcune delle tue dipendenze sono oggetti o funzioni definite all'interno del componente, c'è il rischio che **facciano rieseguire l'Effetto più spesso del necessario.** Per risolvere, rimuovi le dipendenze [oggetto](#removing-unnecessary-object-dependencies) e [funzione](#removing-unnecessary-function-dependencies) non necessarie. Puoi anche [estrarre gli aggiornamenti di state](#updating-state-based-on-previous-state-from-an-effect) e la [logica non reattiva](#reading-the-latest-props-and-state-from-an-effect) fuori dall'Effetto.
-* If your Effect wasn't caused by an interaction (like a click), React will generally let the browser **paint the updated screen first before running your Effect.** If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), replace `useEffect` with [`useLayoutEffect`.](/reference/react/useLayoutEffect)
+* Se il tuo Effetto non è stato causato da un'interazione (come un click), React in genere lascerà che il browser **dipinga lo schermo aggiornato prima di eseguire l'Effetto.** Se il tuo Effetto fa qualcosa di visivo (ad esempio, posizionare un tooltip) e il ritardo è evidente (ad esempio, sfarfalla), sostituisci `useEffect` con [`useLayoutEffect`.](/reference/react/useLayoutEffect)
-* If your Effect is caused by an interaction (like a click), **React may run your Effect before the browser paints the updated screen**. This ensures that the result of the Effect can be observed by the event system. Usually, this works as expected. However, if you must defer the work until after paint, such as an `alert()`, you can use `setTimeout`. See [reactwg/react-18/128](https://github.com/reactwg/react-18/discussions/128) for more information.
+* Se il tuo Effetto è causato da un'interazione (come un click), **React può eseguire l'Effetto prima che il browser dipinga lo schermo aggiornato**. Questo garantisce che il risultato dell'Effetto possa essere osservato dal sistema di eventi. Di solito funziona come previsto. Tuttavia, se devi posticipare il lavoro fino a dopo il paint, come un `alert()`, puoi usare `setTimeout`. Vedi [reactwg/react-18/128](https://github.com/reactwg/react-18/discussions/128) per maggiori informazioni.
-* Even if your Effect was caused by an interaction (like a click), **React may allow the browser to repaint the screen before processing the state updates inside your Effect.** Usually, this works as expected. However, if you must block the browser from repainting the screen, you need to replace `useEffect` with [`useLayoutEffect`.](/reference/react/useLayoutEffect)
+* Anche se il tuo Effetto è stato causato da un'interazione (come un click), **React può permettere al browser di ridipingere lo schermo prima di elaborare gli aggiornamenti di state all'interno dell'Effetto.** Di solito funziona come previsto. Tuttavia, se devi impedire al browser di ridipingere lo schermo, devi sostituire `useEffect` con [`useLayoutEffect`.](/reference/react/useLayoutEffect)
-* Effects **only run on the client.** They don't run during server rendering.
+* Gli Effetti **vengono eseguiti solo sul client.** Non vengono eseguiti durante la renderizzazione lato server.
---
## Usage {/*usage*/}
-### Connecting to an external system {/*connecting-to-an-external-system*/}
+### Connettersi a un sistema esterno {/*connecting-to-an-external-system*/}
-Some components need to stay connected to the network, some browser API, or a third-party library, while they are displayed on the page. These systems aren't controlled by React, so they are called *external.*
+Alcuni componenti devono restare connessi alla rete, a qualche API del browser o a una libreria di terze parti mentre sono visualizzati nella pagina. Questi sistemi non sono controllati da React, quindi vengono chiamati *esterni.*
-To [connect your component to some external system,](/learn/synchronizing-with-effects) call `useEffect` at the top level of your component:
+Per [connettere il tuo componente a un sistema esterno,](/learn/synchronizing-with-effects) chiama `useEffect` al top level del tuo componente:
```js [[1, 8, "const connection = createConnection(serverUrl, roomId);"], [1, 9, "connection.connect();"], [2, 11, "connection.disconnect();"], [3, 13, "[serverUrl, roomId]"]]
import { useState, useEffect } from 'react';
@@ -98,45 +105,45 @@ function ChatRoom({ roomId }) {
}
```
-You need to pass two arguments to `useEffect`:
+Devi passare due argomenti a `useEffect`:
-1. A *setup function* with setup code that connects to that system.
- - It should return a *cleanup function* with cleanup code that disconnects from that system.
-2. A list of dependencies including every value from your component used inside of those functions.
+1. Una *funzione di setup* con codice di setup che si connette a quel sistema.
+ - Dovrebbe restituire una *funzione di cleanup* con codice di cleanup che si disconnette da quel sistema.
+2. Un elenco di dipendenze che include ogni valore del componente usato all'interno di quelle funzioni.
-**React calls your setup and cleanup functions whenever it's necessary, which may happen multiple times:**
+**React chiama le funzioni di setup e cleanup quando è necessario, il che può accadere più volte:**
-1. Your setup code runs when your component is added to the page *(mounts)*.
-2. After every commit of your component where the dependencies have changed:
- - First, your cleanup code runs with the old props and state.
- - Then, your setup code runs with the new props and state.
-3. Your cleanup code runs one final time after your component is removed from the page *(unmounts).*
+1. Il tuo codice di setup viene eseguito quando il componente viene aggiunto alla pagina *(monta)*.
+2. Dopo ogni fase di commit del componente in cui le dipendenze sono cambiate:
+ - Prima, il tuo codice di cleanup viene eseguito con le props e lo state precedenti.
+ - Poi, il tuo codice di setup viene eseguito con le nuove props e il nuovo state.
+3. Il tuo codice di cleanup viene eseguito un'ultima volta dopo che il componente viene rimosso dalla pagina *(smonta)*.
-**Let's illustrate this sequence for the example above.**
+**Illustriamo questa sequenza per l'esempio sopra.**
-When the `ChatRoom` component above gets added to the page, it will connect to the chat room with the initial `serverUrl` and `roomId`. If either `serverUrl` or `roomId` change as a result of a commit (say, if the user picks a different chat room in a dropdown), your Effect will *disconnect from the previous room, and connect to the next one.* When the `ChatRoom` component is removed from the page, your Effect will disconnect one last time.
+Quando il componente `ChatRoom` sopra viene aggiunto alla pagina, si connetterà alla chat room con i valori iniziali di `serverUrl` e `roomId`. Se `serverUrl` o `roomId` cambiano a seguito di una fase di commit (ad esempio, se l'utente sceglie una chat room diversa in un menu a tendina), il tuo Effetto *si disconnetterà dalla room precedente e si connetterà alla successiva.* Quando il componente `ChatRoom` viene rimosso dalla pagina, il tuo Effetto si disconnetterà un'ultima volta.
-**To [help you find bugs,](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) in development React runs setup and cleanup one extra time before the setup.** This is a stress-test that verifies your Effect's logic is implemented correctly. If this causes visible issues, your cleanup function is missing some logic. The cleanup function should stop or undo whatever the setup function was doing. The rule of thumb is that the user shouldn't be able to distinguish between the setup being called once (as in production) and a *setup* → *cleanup* → *setup* sequence (as in development). [See common solutions.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
+**Per [aiutarti a trovare bug,](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) in development React esegue setup e cleanup un'extra volta prima del setup.** È un test di stress che verifica che la logica del tuo Effetto sia implementata correttamente. Se questo causa problemi visibili, alla funzione di cleanup manca della logica. La funzione di cleanup dovrebbe fermare o annullare ciò che faceva la funzione di setup. La regola generale è che l'utente non dovrebbe poter distinguere tra il setup chiamato una volta (come in production) e una sequenza *setup* → *cleanup* → *setup* (come in development). [Vedi soluzioni comuni.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development)
-**Try to [write every Effect as an independent process](/learn/lifecycle-of-reactive-effects#each-effect-represents-a-separate-synchronization-process) and [think about a single setup/cleanup cycle at a time.](/learn/lifecycle-of-reactive-effects#thinking-from-the-effects-perspective)** It shouldn't matter whether your component is mounting, updating, or unmounting. When your cleanup logic correctly "mirrors" the setup logic, your Effect is resilient to running setup and cleanup as often as needed.
+**Cerca di [scrivere ogni Effetto come un processo indipendente](/learn/lifecycle-of-reactive-effects#each-effect-represents-a-separate-synchronization-process) e [pensa a un singolo ciclo setup/cleanup alla volta.](/learn/lifecycle-of-reactive-effects#thinking-from-the-effects-perspective)** Non dovrebbe importare se il componente sta montando, aggiornando o smontando. Quando la logica di cleanup "specchia" correttamente la logica di setup, il tuo Effetto è resiliente all'esecuzione di setup e cleanup quanto spesso serve.
-An Effect lets you [keep your component synchronized](/learn/synchronizing-with-effects) with some external system (like a chat service). Here, *external system* means any piece of code that's not controlled by React, such as:
+Un Effetto ti permette di [mantenere il componente sincronizzato](/learn/synchronizing-with-effects) con un sistema esterno (come un servizio di chat). Qui, *sistema esterno* indica qualsiasi pezzo di codice non controllato da React, come:
-* A timer managed with [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) and [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval).
-* An event subscription using [`window.addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) and [`window.removeEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener).
-* A third-party animation library with an API like `animation.start()` and `animation.reset()`.
+* Un timer gestito con [`setInterval()`](https://developer.mozilla.org/it/docs/Web/API/setInterval) e [`clearInterval()`](https://developer.mozilla.org/it/docs/Web/API/clearInterval).
+* Una sottoscrizione a eventi usando [`window.addEventListener()`](https://developer.mozilla.org/it/docs/Web/API/EventTarget/addEventListener) e [`window.removeEventListener()`](https://developer.mozilla.org/it/docs/Web/API/EventTarget/removeEventListener).
+* Una libreria di animazione di terze parti con un'API come `animation.start()` e `animation.reset()`.
-**If you're not connecting to any external system, [you probably don't need an Effect.](/learn/you-might-not-need-an-effect)**
+**Se non ti stai connettendo a nessun sistema esterno, [probabilmente non ti serve un Effetto.](/learn/you-might-not-need-an-effect)**
-
+
-#### Connecting to a chat server {/*connecting-to-a-chat-server*/}
+#### Connessione a un server di chat {/*connecting-to-a-chat-server*/}
-In this example, the `ChatRoom` component uses an Effect to stay connected to an external system defined in `chat.js`. Press "Open chat" to make the `ChatRoom` component appear. This sandbox runs in development mode, so there is an extra connect-and-disconnect cycle, as [explained here.](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) Try changing the `roomId` and `serverUrl` using the dropdown and the input, and see how the Effect re-connects to the chat. Press "Close chat" to see the Effect disconnect one last time.
+In questo esempio, il componente `ChatRoom` usa un Effetto per restare connesso a un sistema esterno definito in `chat.js`. Premi "Open chat" per far apparire il componente `ChatRoom`. Questa sandbox è in modalità development, quindi c'è un ciclo extra di connessione e disconnessione, come [spiegato qui.](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) Prova a cambiare `roomId` e `serverUrl` usando il menu a tendina e l'input, e osserva come l'Effetto si riconnette alla chat. Premi "Close chat" per vedere l'Effetto disconnettersi un'ultima volta.
@@ -197,7 +204,7 @@ export default function App() {
```js src/chat.js
export function createConnection(serverUrl, roomId) {
- // A real implementation would actually connect to the server
+ // Un'implementazione reale si connetterebbe effettivamente al server
return {
connect() {
console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...');
@@ -218,9 +225,9 @@ button { margin-left: 10px; }
-#### Listening to a global browser event {/*listening-to-a-global-browser-event*/}
+#### Ascoltare un evento globale del browser {/*listening-to-a-global-browser-event*/}
-In this example, the external system is the browser DOM itself. Normally, you'd specify event listeners with JSX, but you can't listen to the global [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object this way. An Effect lets you connect to the `window` object and listen to its events. Listening to the `pointermove` event lets you track the cursor (or finger) position and update the red dot to move with it.
+In questo esempio, il sistema esterno è il DOM del browser stesso. Normalmente specificheresti i listener di eventi con JSX, ma non puoi ascoltare l'oggetto globale [`window`](https://developer.mozilla.org/it/docs/Web/API/Window) in questo modo. Un Effetto ti permette di connetterti all'oggetto `window` e ascoltare i suoi eventi. Ascoltare l'evento `pointermove` ti permette di tracciare la posizione del cursore (o del dito) e aggiornare il punto rosso affinché si muova con esso.
@@ -267,9 +274,9 @@ body {
-#### Triggering an animation {/*triggering-an-animation*/}
+#### Attivare un'animazione {/*triggering-an-animation*/}
-In this example, the external system is the animation library in `animation.js`. It provides a JavaScript class called `FadeInAnimation` that takes a DOM node as an argument and exposes `start()` and `stop()` methods to control the animation. This component [uses a ref](/learn/manipulating-the-dom-with-refs) to access the underlying DOM node. The Effect reads the DOM node from the ref and automatically starts the animation for that node when the component appears.
+In questo esempio, il sistema esterno è la libreria di animazione in `animation.js`. Fornisce una classe JavaScript chiamata `FadeInAnimation` che accetta un nodo DOM come argomento ed espone i metodi `start()` e `stop()` per controllare l'animazione. Questo componente [usa un ref](/learn/manipulating-the-dom-with-refs) per accedere al nodo DOM sottostante. L'Effetto legge il nodo DOM dal ref e avvia automaticamente l'animazione per quel nodo quando il componente appare.
@@ -327,11 +334,11 @@ export class FadeInAnimation {
start(duration) {
this.duration = duration;
if (this.duration === 0) {
- // Jump to end immediately
+ // Salta immediatamente alla fine
this.onProgress(1);
} else {
this.onProgress(0);
- // Start animating
+ // Inizia l'animazione
this.startTime = performance.now();
this.frameId = requestAnimationFrame(() => this.onFrame());
}
@@ -341,7 +348,7 @@ export class FadeInAnimation {
const progress = Math.min(timePassed / this.duration, 1);
this.onProgress(progress);
if (progress < 1) {
- // We still have more frames to paint
+ // Abbiamo ancora altri frame da dipingere
this.frameId = requestAnimationFrame(() => this.onFrame());
}
}
@@ -366,9 +373,9 @@ html, body { min-height: 300px; }
-#### Controlling a modal dialog {/*controlling-a-modal-dialog*/}
+#### Controllare una finestra modale {/*controlling-a-modal-dialog*/}
-In this example, the external system is the browser DOM. The `ModalDialog` component renders a [`