diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md index 1eec63388..8c782d6b9 100644 --- a/src/content/learn/synchronizing-with-effects.md +++ b/src/content/learn/synchronizing-with-effects.md @@ -1,65 +1,72 @@ --- -title: 'Synchronizing with Effects' +title: Sincronizzare con gli Effetti +translationStatus: ai-draft --- + + +Questa pagina è stata tradotta automaticamente e potrebbe beneficiare di una revisione umana. [Migliora questa traduzione](https://github.com/reactjs/it.react.dev/edit/main/src/content/learn/synchronizing-with-effects.md). + + + -Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. *Effects* let you run some code after rendering so that you can synchronize your component with some system outside of React. +Alcuni componenti devono sincronizzarsi con sistemi esterni. Per esempio, potresti voler controllare un componente non-React in base allo state di React, impostare una connessione al server o inviare un log di analytics quando un componente appare sullo schermo. Gli *Effetti* ti permettono di eseguire del codice dopo la renderizzazione, così da sincronizzare il tuo componente con un sistema esterno a React. -- What Effects are -- How Effects are different from events -- How to declare an Effect in your component -- How to skip re-running an Effect unnecessarily -- Why Effects run twice in development and how to fix them +- Cosa sono gli Effetti +- In che modo gli Effetti sono diversi dagli eventi +- Come dichiarare un Effetto nel tuo componente +- Come evitare di rieseguire un Effetto inutilmente +- Perché gli Effetti girano due volte in modalità di sviluppo e come risolvere il problema -## What are Effects and how are they different from events? {/*what-are-effects-and-how-are-they-different-from-events*/} +## Cosa sono gli Effetti e in che modo sono diversi dagli eventi? {/*what-are-effects-and-how-are-they-different-from-events*/} -Before getting to Effects, you need to be familiar with two types of logic inside React components: +Prima di arrivare agli Effetti, devi conoscere due tipi di logica all'interno dei componenti React: -- **Rendering code** (introduced in [Describing the UI](/learn/describing-the-ui)) lives at the top level of your component. This is where you take the props and state, transform them, and return the JSX you want to see on the screen. [Rendering code must be pure.](/learn/keeping-components-pure) Like a math formula, it should only _calculate_ the result, but not do anything else. +- **Il codice di renderizzazione** (introdotto in [Descrivere l'UI](/learn/describing-the-ui)) vive al top level del tuo componente. Qui prendi le props e lo state, li trasformi e restituisci il JSX che vuoi vedere sullo schermo. [Il codice di renderizzazione deve essere puro.](/learn/keeping-components-pure) Come una formula matematica, dovrebbe solo _calcolare_ il risultato, senza fare altro. -- **Event handlers** (introduced in [Adding Interactivity](/learn/adding-interactivity)) are nested functions inside your components that *do* things rather than just calculate them. An event handler might update an input field, submit an HTTP POST request to buy a product, or navigate the user to another screen. Event handlers contain ["side effects"](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) (they change the program's state) caused by a specific user action (for example, a button click or typing). +- I **gestori di eventi** (introdotti in [Aggiungere le Interazioni](/learn/adding-interactivity)) sono funzioni annidate all'interno dei tuoi componenti che _fanno_ cose invece di limitarsi a calcolarle. Un gestore di eventi potrebbe aggiornare un campo di input, inviare una richiesta HTTP POST per acquistare un prodotto o navigare l'utente verso un'altra schermata. I gestori di eventi contengono ["effetti collaterali"](https://it.wikipedia.org/wiki/Effetto_collaterale_(informatica)) (cambiano lo state del programma) causati da un'azione specifica dell'utente (per esempio, un click su un pulsante o la digitazione). -Sometimes this isn't enough. Consider a `ChatRoom` component that must connect to the chat server whenever it's visible on the screen. Connecting to a server is not a pure calculation (it's a side effect) so it can't happen during rendering. However, there is no single particular event like a click that causes `ChatRoom` to be displayed. +A volte questo non basta. Considera un componente `ChatRoom` che deve connettersi al server di chat ogni volta che è visibile sullo schermo. Connettersi a un server non è un calcolo puro (è un effetto collaterale), quindi non può avvenire durante la renderizzazione. Tuttavia, non c'è un singolo evento particolare come un click che fa apparire `ChatRoom`. -***Effects* let you specify side effects that are caused by rendering itself, rather than by a particular event.** Sending a message in the chat is an *event* because it is directly caused by the user clicking a specific button. However, setting up a server connection is an *Effect* because it should happen no matter which interaction caused the component to appear. Effects run at the end of a [commit](/learn/render-and-commit) after the screen updates. This is a good time to synchronize the React components with some external system (like network or a third-party library). +**Gli *Effetti* ti permettono di specificare effetti collaterali causati dalla renderizzazione stessa, piuttosto che da un evento particolare.** Inviare un messaggio in chat è un _evento_ perché è causato direttamente dall'utente che clicca un pulsante specifico. Tuttavia, impostare una connessione al server è un _Effetto_ perché dovrebbe avvenire indipendentemente da quale interazione ha fatto apparire il componente. Gli Effetti girano alla fine della [fase di commit](/learn/render-and-commit) dopo l'aggiornamento dello schermo. È un buon momento per sincronizzare i componenti React con un sistema esterno (come la rete o una libreria di terze parti). -Here and later in this text, capitalized "Effect" refers to the React-specific definition above, i.e. a side effect caused by rendering. To refer to the broader programming concept, we'll say "side effect". +Qui e più avanti in questo testo, "Effetto" con la maiuscola si riferisce alla definizione specifica di React sopra, cioè un effetto collaterale causato dalla renderizzazione. Per riferirci al concetto più ampio della programmazione, diremo "effetto collaterale". -## You might not need an Effect {/*you-might-not-need-an-effect*/} +## Potresti non avere bisogno di un Effetto {/*you-might-not-need-an-effect*/} -**Don't rush to add Effects to your components.** Keep in mind that Effects are typically used to "step out" of your React code and synchronize with some *external* system. This includes browser APIs, third-party widgets, network, and so on. If your Effect only adjusts some state based on other state, [you might not need an Effect.](/learn/you-might-not-need-an-effect) +**Non affrettarti ad aggiungere Effetti ai tuoi componenti.** Tieni presente che gli Effetti vengono tipicamente usati per "uscire" dal tuo codice React e sincronizzarsi con un sistema _esterno_. Questo include le API del browser, widget di terze parti, la rete e così via. Se il tuo Effetto regola solo dello state in base ad altro state, [potresti non avere bisogno di un Effetto.](/learn/you-might-not-need-an-effect) -## How to write an Effect {/*how-to-write-an-effect*/} +## Come scrivere un Effetto {/*how-to-write-an-effect*/} -To write an Effect, follow these three steps: +Per scrivere un Effetto, segui questi tre passaggi: -1. **Declare an Effect.** By default, your Effect will run after every [commit](/learn/render-and-commit). -2. **Specify the Effect dependencies.** Most Effects should only re-run *when needed* rather than after every render. For example, a fade-in animation should only trigger when a component appears. Connecting and disconnecting to a chat room should only happen when the component appears and disappears, or when the chat room changes. You will learn how to control this by specifying *dependencies.* -3. **Add cleanup if needed.** Some Effects need to specify how to stop, undo, or clean up whatever they were doing. For example, "connect" needs "disconnect", "subscribe" needs "unsubscribe", and "fetch" needs either "cancel" or "ignore". You will learn how to do this by returning a *cleanup function*. +1. **Dichiarare un Effetto.** Per impostazione predefinita, il tuo Effetto girerà dopo ogni [fase di commit](/learn/render-and-commit). +2. **Specificare le dipendenze dell'Effetto.** La maggior parte degli Effetti dovrebbe rieseguirsi solo _quando necessario_ invece che dopo ogni renderizzazione. Per esempio, un'animazione fade-in dovrebbe attivarsi solo quando un componente appare. Connettersi e disconnettersi da una chat room dovrebbe avvenire solo quando il componente appare e scompare, o quando cambia la chat room. Imparerai a controllare questo specificando le _dipendenze._ +3. **Aggiungere la cleanup se necessario.** Alcuni Effetti devono specificare come fermare, annullare o ripulire ciò che stavano facendo. Per esempio, "connect" ha bisogno di "disconnect", "subscribe" ha bisogno di "unsubscribe" e "fetch" ha bisogno di "cancel" o "ignore". Imparerai a farlo restituendo una _funzione di cleanup_. -Let's look at each of these steps in detail. +Vediamo ciascuno di questi passaggi in dettaglio. -### Step 1: Declare an Effect {/*step-1-declare-an-effect*/} +### Passo 1: Dichiarare un Effetto {/*step-1-declare-an-effect*/} -To declare an Effect in your component, import the [`useEffect` Hook](/reference/react/useEffect) from React: +Per dichiarare un Effetto nel tuo componente, importa l'Hook [`useEffect`](/reference/react/useEffect) da React: ```js import { useEffect } from 'react'; ``` -Then, call it at the top level of your component and put some code inside your Effect: +Poi, chiamalo al top level del tuo componente e inserisci del codice all'interno del tuo Effetto: ```js {2-4} function MyComponent() { @@ -70,15 +77,15 @@ function MyComponent() { } ``` -Every time your component renders, React will update the screen *and then* run the code inside `useEffect`. In other words, **`useEffect` "delays" a piece of code from running until that render is reflected on the screen.** +Ogni volta che il tuo componente viene renderizzato, React aggiornerà lo schermo _e poi_ eseguirà il codice all'interno di `useEffect`. In altre parole, **`useEffect` "ritarda" l'esecuzione di un pezzo di codice finché quella renderizzazione non si riflette sullo schermo.** -Let's see how you can use an Effect to synchronize with an external system. Consider a `` React component. It would be nice to control whether it's playing or paused by passing an `isPlaying` prop to it: +Vediamo come puoi usare un Effetto per sincronizzarti con un sistema esterno. Considera un componente React ``. Sarebbe bello controllare se è in riproduzione o in pausa passandogli una prop `isPlaying`: ```js ; ``` -Your custom `VideoPlayer` component renders the built-in browser [`