From b2da603ba5f85623003697ef12cd0d90a5459a06 Mon Sep 17 00:00:00 2001 From: Alessandro De Blasis Date: Mon, 14 Sep 2026 22:48:33 +0300 Subject: [PATCH] translate(reference): useState Signed-off-by: Alessandro De Blasis --- src/content/reference/react/useState.md | 287 ++++++++++++------------ 1 file changed, 147 insertions(+), 140 deletions(-) diff --git a/src/content/reference/react/useState.md b/src/content/reference/react/useState.md index 21911f0ad..23cc3d267 100644 --- a/src/content/reference/react/useState.md +++ b/src/content/reference/react/useState.md @@ -1,10 +1,17 @@ --- title: useState +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/useState.md). + + + -`useState` is a React Hook that lets you add a [state variable](/learn/state-a-components-memory) to your component. +`useState` è un Hook React che ti permette di aggiungere una [variabile di state](/learn/state-a-components-memory) al tuo componente. ```js const [state, setState] = useState(initialState) @@ -20,7 +27,7 @@ const [state, setState] = useState(initialState) ### `useState(initialState)` {/*usestate*/} -Call `useState` at the top level of your component to declare a [state variable.](/learn/state-a-components-memory) +Chiama `useState` al top level del tuo componente per dichiarare una [variabile di state.](/learn/state-a-components-memory) ```js import { useState } from 'react'; @@ -32,32 +39,32 @@ function MyComponent() { // ... ``` -The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment) +La convenzione è di nominare le variabili di state come `[something, setSomething]` usando la [destructuring di array.](https://javascript.info/destructuring-assignment) -[See more examples below.](#usage) +[Vedi altri esempi sotto.](#usage) #### Parameters {/*parameters*/} -* `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render. - * If you pass a function as `initialState`, it will be treated as an _initializer function_. It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state. [See an example below.](#avoiding-recreating-the-initial-state) +* `initialState`: Il valore con cui vuoi che lo state sia inizialmente. Può essere un valore di qualsiasi tipo, ma c'è un comportamento speciale per le funzioni. Questo argomento viene ignorato dopo la renderizzazione iniziale. + * Se passi una funzione come `initialState`, verrà trattata come una _funzione di inizializzazione_. Deve essere pura, non deve accettare argomenti e deve restituire un valore di qualsiasi tipo. React chiamerà la tua funzione di inizializzazione quando inizializza il componente e memorizzerà il suo valore di ritorno come state iniziale. [Vedi un esempio sotto.](#avoiding-recreating-the-initial-state) #### Returns {/*returns*/} -`useState` returns an array with exactly two values: +`useState` restituisce un array con esattamente due valori: -1. The current state. During the first render, it will match the `initialState` you have passed. -2. The [`set` function](#setstate) that lets you update the state to a different value and trigger a re-render. +1. Lo state corrente. Durante la prima renderizzazione, corrisponderà all'`initialState` che hai passato. +2. La [funzione `set`](#setstate) che ti permette di aggiornare lo state a un valore diverso e avviare una ri-renderizzazione. #### Caveats {/*caveats*/} -* `useState` 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. -* In Strict Mode, React will **call your initializer function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your initializer function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored. +* `useState` è un Hook, quindi puoi chiamarlo solo **al top level del tuo componente** o dei tuoi Hooks. Non puoi chiamarlo all'interno di loop o condizioni. Se ne hai bisogno, estrai un nuovo componente e sposta lo state al suo interno. +* In Strict Mode, React **chiamerà la tua funzione di inizializzazione due volte** per [aiutarti a trovare impurità accidentali.](#my-initializer-or-updater-function-runs-twice) Questo è un comportamento solo in development e non influisce sulla production. Se la tua funzione di inizializzazione è pura (come dovrebbe essere), non dovrebbe influire sul comportamento. Il risultato di una delle chiamate viene ignorato. --- -### `set` functions, like `setSomething(nextState)` {/*setstate*/} +### Funzioni `set`, come `setSomething(nextState)` {/*setstate*/} -The `set` function returned by `useState` lets you update the state to a different value and trigger a re-render. You can pass the next state directly, or a function that calculates it from the previous state: +La funzione `set` restituita da `useState` ti permette di aggiornare lo state a un valore diverso e avviare una ri-renderizzazione. Puoi passare il prossimo state direttamente, oppure una funzione che lo calcola dallo state precedente: ```js const [name, setName] = useState('Edward'); @@ -70,34 +77,34 @@ function handleClick() { #### Parameters {/*setstate-parameters*/} -* `nextState`: The value that you want the state to be. It can be a value of any type, but there is a special behavior for functions. - * If you pass a function as `nextState`, it will be treated as an _updater function_. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state. [See an example below.](#updating-state-based-on-the-previous-state) +* `nextState`: Il valore con cui vuoi che lo state sia. Può essere un valore di qualsiasi tipo, ma c'è un comportamento speciale per le funzioni. + * Se passi una funzione come `nextState`, verrà trattata come una _funzione di aggiornamento dello state_. Deve essere pura, deve accettare lo state in attesa come unico argomento e deve restituire il prossimo state. React metterà la tua funzione di aggiornamento dello state in una coda e ri-renderizzerà il tuo componente. Durante la prossima renderizzazione, React calcolerà il prossimo state applicando tutte le funzioni di aggiornamento in coda allo state precedente. [Vedi un esempio sotto.](#updating-state-based-on-the-previous-state) #### Returns {/*setstate-returns*/} -`set` functions do not have a return value. +Le funzioni `set` non hanno un valore di ritorno. #### Caveats {/*setstate-caveats*/} -* The `set` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `set` function, [you will still get the old value](#ive-updated-the-state-but-logging-gives-me-the-old-value) that was on the screen before your call. +* La funzione `set` **aggiorna la variabile di state solo per la *prossima* renderizzazione**. Se leggi la variabile di state dopo aver chiamato la funzione `set`, [otterrai comunque il vecchio valore](#ive-updated-the-state-but-logging-gives-me-the-old-value) che era sullo schermo prima della tua chiamata. -* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. Although in some cases React may still need to call your component before skipping the children, it shouldn't affect your code. +* Se il nuovo valore che fornisci è identico allo `state` corrente, come determinato da un confronto [`Object.is`](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/is), React **salterà la ri-renderizzazione del componente e dei suoi figli.** Si tratta di un'ottimizzazione. Anche se in alcuni casi React potrebbe comunque dover chiamare il tuo componente prima di ignorare i figli, non dovrebbe influire sul tuo codice. -* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/reference/react-dom/flushSync) +* React [raggruppa gli aggiornamenti di state.](/learn/queueing-a-series-of-state-updates) Aggiorna lo schermo **dopo che tutti i gestori di eventi sono stati eseguiti** e hanno chiamato le loro funzioni `set`. Questo previene più ri-renderizzazioni durante un singolo evento. Nel raro caso in cui devi forzare React ad aggiornare lo schermo prima, per esempio per accedere al DOM, puoi usare [`flushSync`.](/reference/react-dom/flushSync) -* The `set` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect) +* La funzione `set` ha un'identità stabile, quindi spesso la vedrai omessa dalle dipendenze degli Effetti, ma includerla non farà scattare l'Effetto. Se il linter ti permette di omettere una dipendenza senza errori, è sicuro farlo. [Scopri di più sulla rimozione delle dipendenze degli Effetti.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect) -* Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example below.](#storing-information-from-previous-renders) +* Chiamare la funzione `set` *durante la renderizzazione* è consentito solo dall'interno del componente attualmente in renderizzazione. React scarterà il suo output e tenterà immediatamente di renderizzarlo di nuovo con il nuovo state. Questo pattern è raramente necessario, ma puoi usarlo per **memorizzare informazioni dalle renderizzazioni precedenti**. [Vedi un esempio sotto.](#storing-information-from-previous-renders) -* In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored. +* In Strict Mode, React **chiamerà la tua funzione di aggiornamento dello state due volte** per [aiutarti a trovare impurità accidentali.](#my-initializer-or-updater-function-runs-twice) Questo è un comportamento solo in development e non influisce sulla production. Se la tua funzione di aggiornamento dello state è pura (come dovrebbe essere), non dovrebbe influire sul comportamento. Il risultato di una delle chiamate viene ignorato. --- ## Usage {/*usage*/} -### Adding state to a component {/*adding-state-to-a-component*/} +### Aggiungere state a un componente {/*adding-state-to-a-component*/} -Call `useState` at the top level of your component to declare one or more [state variables.](/learn/state-a-components-memory) +Chiama `useState` al top level del tuo componente per dichiarare una o più [variabili di state.](/learn/state-a-components-memory) ```js [[1, 4, "age"], [2, 4, "setAge"], [3, 4, "42"], [1, 5, "name"], [2, 5, "setName"], [3, 5, "'Taylor'"]] import { useState } from 'react'; @@ -108,14 +115,14 @@ function MyComponent() { // ... ``` -The convention is to name state variables like `[something, setSomething]` using [array destructuring.](https://javascript.info/destructuring-assignment) +La convenzione è di nominare le variabili di state come `[something, setSomething]` usando la [destructuring di array.](https://javascript.info/destructuring-assignment) -`useState` returns an array with exactly two items: +`useState` restituisce un array con esattamente due elementi: -1. The current state of this state variable, initially set to the initial state you provided. -2. The `set` function that lets you change it to any other value in response to interaction. +1. Lo state corrente di questa variabile di state, inizialmente impostato allo state iniziale che hai fornito. +2. La funzione `set` che ti permette di cambiarlo in qualsiasi altro valore in risposta all'interazione. -To update what’s on the screen, call the `set` function with some next state: +Per aggiornare ciò che c'è sullo schermo, chiama la funzione `set` con un prossimo state: ```js [[2, 2, "setName"]] function handleClick() { @@ -123,28 +130,28 @@ function handleClick() { } ``` -React will store the next state, render your component again with the new values, and update the UI. +React memorizzerà il prossimo state, renderizzerà di nuovo il tuo componente con i nuovi valori e aggiornerà l'UI. -Calling the `set` function [**does not** change the current state in the already executing code](#ive-updated-the-state-but-logging-gives-me-the-old-value): +Chiamare la funzione `set` [**non** cambia lo state corrente nel codice già in esecuzione](#ive-updated-the-state-but-logging-gives-me-the-old-value): ```js {3} function handleClick() { setName('Robin'); - console.log(name); // Still "Taylor"! + console.log(name); // Ancora "Taylor"! } ``` -It only affects what `useState` will return starting from the *next* render. +Influisce solo su ciò che `useState` restituirà a partire dalla *prossima* renderizzazione. - + -#### Counter (number) {/*counter-number*/} +#### Contatore (numero) {/*counter-number*/} -In this example, the `count` state variable holds a number. Clicking the button increments it. +In questo esempio, la variabile di state `count` contiene un numero. Cliccare il pulsante la incrementa. @@ -170,9 +177,9 @@ export default function Counter() { -#### Text field (string) {/*text-field-string*/} +#### Campo di testo (stringa) {/*text-field-string*/} -In this example, the `text` state variable holds a string. When you type, `handleChange` reads the latest input value from the browser input DOM element, and calls `setText` to update the state. This allows you to display the current `text` below. +In questo esempio, la variabile di state `text` contiene una stringa. Quando digiti, `handleChange` legge l'ultimo valore dell'input dall'elemento DOM input del browser e chiama `setText` per aggiornare lo state. Questo ti permette di visualizzare il `text` corrente sotto. @@ -202,9 +209,9 @@ export default function MyInput() { -#### Checkbox (boolean) {/*checkbox-boolean*/} +#### Checkbox (booleano) {/*checkbox-boolean*/} -In this example, the `liked` state variable holds a boolean. When you click the input, `setLiked` updates the `liked` state variable with whether the browser checkbox input is checked. The `liked` variable is used to render the text below the checkbox. +In questo esempio, la variabile di state `liked` contiene un booleano. Quando clicchi l'input, `setLiked` aggiorna la variabile di state `liked` con il valore checked dell'input checkbox del browser. La variabile `liked` viene usata per renderizzare il testo sotto la checkbox. @@ -238,9 +245,9 @@ export default function MyCheckbox() { -#### Form (two variables) {/*form-two-variables*/} +#### Form (due variabili) {/*form-two-variables*/} -You can declare more than one state variable in the same component. Each state variable is completely independent. +Puoi dichiarare più di una variabile di state nello stesso componente. Ogni variabile di state è completamente indipendente. @@ -278,9 +285,9 @@ button { display: block; margin-top: 10px; } --- -### Updating state based on the previous state {/*updating-state-based-on-the-previous-state*/} +### Aggiornare lo state in base allo state precedente {/*updating-state-based-on-the-previous-state*/} -Suppose the `age` is `42`. This handler calls `setAge(age + 1)` three times: +Supponiamo che `age` sia `42`. Questo gestore chiama `setAge(age + 1)` tre volte: ```js function handleClick() { @@ -290,9 +297,9 @@ function handleClick() { } ``` -However, after one click, `age` will only be `43` rather than `45`! This is because calling the `set` function [does not update](/learn/state-as-a-snapshot) the `age` state variable in the already running code. So each `setAge(age + 1)` call becomes `setAge(43)`. +Tuttavia, dopo un click, `age` sarà solo `43` anziché `45`! Questo perché chiamare la funzione `set` [non aggiorna](/learn/state-as-a-snapshot) la variabile di state `age` nel codice già in esecuzione. Quindi ogni chiamata a `setAge(age + 1)` diventa `setAge(43)`. -To solve this problem, **you may pass an *updater function*** to `setAge` instead of the next state: +Per risolvere questo problema, **puoi passare una *funzione di aggiornamento dello state*** a `setAge` invece del prossimo state: ```js [[1, 2, "a", 0], [2, 2, "a + 1"], [1, 3, "a", 0], [2, 3, "a + 1"], [1, 4, "a", 0], [2, 4, "a + 1"]] function handleClick() { @@ -302,39 +309,39 @@ function handleClick() { } ``` -Here, `a => a + 1` is your updater function. It takes the pending state and calculates the next state from it. +Qui, `a => a + 1` è la tua funzione di aggiornamento dello state. Prende lo state in attesa e calcola il prossimo state da esso. -React puts your updater functions in a [queue.](/learn/queueing-a-series-of-state-updates) Then, during the next render, it will call them in the same order: +React mette le tue funzioni di aggiornamento dello state in una [coda.](/learn/queueing-a-series-of-state-updates) Poi, durante la prossima renderizzazione, le chiamerà nello stesso ordine: -1. `a => a + 1` will receive `42` as the pending state and return `43` as the next state. -1. `a => a + 1` will receive `43` as the pending state and return `44` as the next state. -1. `a => a + 1` will receive `44` as the pending state and return `45` as the next state. +1. `a => a + 1` riceverà `42` come state in attesa e restituirà `43` come prossimo state. +1. `a => a + 1` riceverà `43` come state in attesa e restituirà `44` come prossimo state. +1. `a => a + 1` riceverà `44` come state in attesa e restituirà `45` come prossimo state. -There are no other queued updates, so React will store `45` as the current state in the end. +Non ci sono altri aggiornamenti in coda, quindi React memorizzerà `45` come state corrente alla fine. -By convention, it's common to name the pending state argument for the first letter of the state variable name, like `a` for `age`. However, you may also call it like `prevAge` or something else that you find clearer. +Per convenzione, è comune nominare l'argomento dello state in attesa con la prima lettera del nome della variabile di state, come `a` per `age`. Tuttavia, puoi anche chiamarlo `prevAge` o qualcos'altro che trovi più chiaro. -React may [call your updaters twice](#my-initializer-or-updater-function-runs-twice) in development to verify that they are [pure.](/learn/keeping-components-pure) +React potrebbe [chiamare le tue funzioni di aggiornamento due volte](#my-initializer-or-updater-function-runs-twice) in development per verificare che siano [pure.](/learn/keeping-components-pure) -#### Is using an updater always preferred? {/*is-using-an-updater-always-preferred*/} +#### Usare sempre una funzione di aggiornamento è preferibile? {/*is-using-an-updater-always-preferred*/} -You might hear a recommendation to always write code like `setAge(a => a + 1)` if the state you're setting is calculated from the previous state. There is no harm in it, but it is also not always necessary. +Potresti sentire il consiglio di scrivere sempre codice come `setAge(a => a + 1)` se lo state che stai impostando viene calcolato dallo state precedente. Non c'è nulla di male, ma non è sempre necessario. -In most cases, there is no difference between these two approaches. React always makes sure that for intentional user actions, like clicks, the `age` state variable would be updated before the next click. This means there is no risk of a click handler seeing a "stale" `age` at the beginning of the event handler. +Nella maggior parte dei casi, non c'è differenza tra questi due approcci. React si assicura sempre che, per azioni intenzionali dell'utente come i click, la variabile di state `age` venga aggiornata prima del click successivo. Questo significa che non c'è rischio che un gestore di eventi veda un valore `age` "obsoleto" all'inizio del gestore di eventi. -However, if you do multiple updates within the same event, updaters can be helpful. They're also helpful if accessing the state variable itself is inconvenient (you might run into this when optimizing re-renders). +Tuttavia, se esegui più aggiornamenti nello stesso evento, le funzioni di aggiornamento dello state possono essere utili. Sono utili anche se accedere alla variabile di state stessa è scomodo (potresti imbatterti in questo quando ottimizzi le ri-renderizzazioni). -If you prefer consistency over slightly more verbose syntax, it's reasonable to always write an updater if the state you're setting is calculated from the previous state. If it's calculated from the previous state of some *other* state variable, you might want to combine them into one object and [use a reducer.](/learn/extracting-state-logic-into-a-reducer) +Se preferisci la coerenza a una sintassi leggermente più verbosa, è ragionevole scrivere sempre una funzione di aggiornamento dello state se lo state che stai impostando viene calcolato dallo state precedente. Se viene calcolato dallo state precedente di qualche *altra* variabile di state, potresti volerle combinare in un oggetto e [usare un reducer.](/learn/extracting-state-logic-into-a-reducer) - + -#### Passing the updater function {/*passing-the-updater-function*/} +#### Passare la funzione di aggiornamento dello state {/*passing-the-updater-function*/} -This example passes the updater function, so the "+3" button works. +Questo esempio passa la funzione di aggiornamento dello state, quindi il pulsante "+3" funziona. @@ -373,9 +380,9 @@ h1 { display: block; margin: 10px; } -#### Passing the next state directly {/*passing-the-next-state-directly*/} +#### Passare il prossimo state direttamente {/*passing-the-next-state-directly*/} -This example **does not** pass the updater function, so the "+3" button **doesn't work as intended**. +Questo esempio **non** passa la funzione di aggiornamento dello state, quindi il pulsante "+3" **non funziona come previsto**. @@ -418,32 +425,32 @@ h1 { display: block; margin: 10px; } --- -### Updating objects and arrays in state {/*updating-objects-and-arrays-in-state*/} +### Aggiornare oggetti e array nello state {/*updating-objects-and-arrays-in-state*/} -You can put objects and arrays into state. In React, state is considered read-only, so **you should *replace* it rather than *mutate* your existing objects**. For example, if you have a `form` object in state, don't mutate it: +Puoi mettere oggetti e array nello state. In React, lo state è considerato di sola lettura, quindi **dovresti *sostituirlo* anziché *mutare* i tuoi oggetti esistenti**. Per esempio, se hai un oggetto `form` nello state, non mutarlo: ```js -// 🚩 Don't mutate an object in state like this: +// 🚩 Non mutare un oggetto nello state così: form.firstName = 'Taylor'; ``` -Instead, replace the whole object by creating a new one: +Invece, sostituisci l'intero oggetto creandone uno nuovo: ```js -// ✅ Replace state with a new object +// ✅ Sostituisci lo state con un nuovo oggetto setForm({ ...form, firstName: 'Taylor' }); ``` -Read [updating objects in state](/learn/updating-objects-in-state) and [updating arrays in state](/learn/updating-arrays-in-state) to learn more. +Leggi [aggiornare oggetti nello state](/learn/updating-objects-in-state) e [aggiornare array nello state](/learn/updating-arrays-in-state) per saperne di più. - + -#### Form (object) {/*form-object*/} +#### Form (oggetto) {/*form-object*/} -In this example, the `form` state variable holds an object. Each input has a change handler that calls `setForm` with the next state of the entire form. The `{ ...form }` spread syntax ensures that the state object is replaced rather than mutated. +In questo esempio, la variabile di state `form` contiene un oggetto. Ogni input ha un gestore di modifica che chiama `setForm` con il prossimo state dell'intero form. La sintassi spread `{ ...form }` assicura che l'oggetto state venga sostituito anziché mutato. @@ -514,9 +521,9 @@ input { margin-left: 5px; } -#### Form (nested object) {/*form-nested-object*/} +#### Form (oggetto annidato) {/*form-nested-object*/} -In this example, the state is more nested. When you update nested state, you need to create a copy of the object you're updating, as well as any objects "containing" it on the way upwards. Read [updating a nested object](/learn/updating-objects-in-state#updating-a-nested-object) to learn more. +In questo esempio, lo state è più annidato. Quando aggiorni uno state annidato, devi creare una copia dell'oggetto che stai aggiornando, così come di tutti gli oggetti che lo "contengono" risalendo verso l'alto. Leggi [aggiornare un oggetto annidato](/learn/updating-objects-in-state#updating-a-nested-object) per saperne di più. @@ -626,9 +633,9 @@ img { width: 200px; height: 200px; } -#### List (array) {/*list-array*/} +#### Lista (array) {/*list-array*/} -In this example, the `todos` state variable holds an array. Each button handler calls `setTodos` with the next version of that array. The `[...todos]` spread syntax, `todos.map()` and `todos.filter()` ensure the state array is replaced rather than mutated. +In questo esempio, la variabile di state `todos` contiene un array. Ogni gestore di pulsante chiama `setTodos` con la prossima versione di quell'array. La sintassi spread `[...todos]`, `todos.map()` e `todos.filter()` assicurano che l'array state venga sostituito anziché mutato. @@ -793,9 +800,9 @@ ul, li { margin: 0; padding: 0; } -#### Writing concise update logic with Immer {/*writing-concise-update-logic-with-immer*/} +#### Scrivere logica di aggiornamento concisa con Immer {/*writing-concise-update-logic-with-immer*/} -If updating arrays and objects without mutation feels tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer) to reduce repetitive code. Immer lets you write concise code as if you were mutating objects, but under the hood it performs immutable updates: +Se aggiornare array e oggetti senza mutazione ti sembra tedioso, puoi usare una libreria come [Immer](https://github.com/immerjs/use-immer) per ridurre il codice ripetitivo. Immer ti permette di scrivere codice conciso come se stessi mutando oggetti, ma sotto il cofano esegue aggiornamenti immutabili: @@ -884,9 +891,9 @@ function ItemList({ artworks, onToggle }) { --- -### Avoiding recreating the initial state {/*avoiding-recreating-the-initial-state*/} +### Evitare di ricreare lo state iniziale {/*avoiding-recreating-the-initial-state*/} -React saves the initial state once and ignores it on the next renders. +React salva lo state iniziale una volta e lo ignora nelle renderizzazioni successive. ```js function TodoList() { @@ -894,9 +901,9 @@ function TodoList() { // ... ``` -Although the result of `createInitialTodos()` is only used for the initial render, you're still calling this function on every render. This can be wasteful if it's creating large arrays or performing expensive calculations. +Sebbene il risultato di `createInitialTodos()` venga usato solo per la renderizzazione iniziale, stai comunque chiamando questa funzione a ogni renderizzazione. Può essere inefficiente se crea array grandi o esegue calcoli costosi. -To solve this, you may **pass it as an _initializer_ function** to `useState` instead: +Per risolvere, puoi **passarla come _funzione di inizializzazione_** a `useState`: ```js function TodoList() { @@ -904,15 +911,15 @@ function TodoList() { // ... ``` -Notice that you’re passing `createInitialTodos`, which is the *function itself*, and not `createInitialTodos()`, which is the result of calling it. If you pass a function to `useState`, React will only call it during initialization. +Nota che stai passando `createInitialTodos`, cioè la *funzione stessa*, e non `createInitialTodos()`, che è il risultato della sua chiamata. Se passi una funzione a `useState`, React la chiamerà solo durante l'inizializzazione. -React may [call your initializers twice](#my-initializer-or-updater-function-runs-twice) in development to verify that they are [pure.](/learn/keeping-components-pure) +React potrebbe [chiamare le tue funzioni di inizializzazione due volte](#my-initializer-or-updater-function-runs-twice) in development per verificare che siano [pure.](/learn/keeping-components-pure) - + -#### Passing the initializer function {/*passing-the-initializer-function*/} +#### Passare la funzione di inizializzazione {/*passing-the-initializer-function*/} -This example passes the initializer function, so the `createInitialTodos` function only runs during initialization. It does not run when component re-renders, such as when you type into the input. +Questo esempio passa la funzione di inizializzazione, quindi la funzione `createInitialTodos` viene eseguita solo durante l'inizializzazione. Non viene eseguita quando il componente si ri-renderizza, ad esempio quando digiti nell'input. @@ -963,9 +970,9 @@ export default function TodoList() { -#### Passing the initial state directly {/*passing-the-initial-state-directly*/} +#### Passare lo state iniziale direttamente {/*passing-the-initial-state-directly*/} -This example **does not** pass the initializer function, so the `createInitialTodos` function runs on every render, such as when you type into the input. There is no observable difference in behavior, but this code is less efficient. +Questo esempio **non** passa la funzione di inizializzazione, quindi la funzione `createInitialTodos` viene eseguita a ogni renderizzazione, ad esempio quando digiti nell'input. Non c'è differenza osservabile nel comportamento, ma questo codice è meno efficiente. @@ -1020,13 +1027,13 @@ export default function TodoList() { --- -### Resetting state with a key {/*resetting-state-with-a-key*/} +### Reimpostare lo state con una key {/*resetting-state-with-a-key*/} -You'll often encounter the `key` attribute when [rendering lists.](/learn/rendering-lists) However, it also serves another purpose. +Incontrerai spesso l'attributo `key` quando [renderizzi liste.](/learn/rendering-lists) Tuttavia, serve anche a un altro scopo. -You can **reset a component's state by passing a different `key` to a component.** In this example, the Reset button changes the `version` state variable, which we pass as a `key` to the `Form`. When the `key` changes, React re-creates the `Form` component (and all of its children) from scratch, so its state gets reset. +Puoi **reimpostare lo state di un componente passando una `key` diversa a un componente.** In questo esempio, il pulsante Reset cambia la variabile di state `version`, che passiamo come `key` al `Form`. Quando la `key` cambia, React ricrea il componente `Form` (e tutti i suoi figli) da zero, quindi il suo state viene reimpostato. -Read [preserving and resetting state](/learn/preserving-and-resetting-state) to learn more. +Leggi [Preserving and Resetting State](/learn/preserving-and-resetting-state) per saperne di più. @@ -1071,19 +1078,19 @@ button { display: block; margin-bottom: 20px; } --- -### Storing information from previous renders {/*storing-information-from-previous-renders*/} +### Memorizzare informazioni dalle renderizzazioni precedenti {/*storing-information-from-previous-renders*/} -Usually, you will update state in event handlers. However, in rare cases you might want to adjust state in response to rendering -- for example, you might want to change a state variable when a prop changes. +Di solito, aggiornerai lo state nei gestori di eventi. Tuttavia, in rari casi potresti voler regolare lo state in risposta alla renderizzazione — per esempio, potresti voler cambiare una variabile di state quando una prop cambia. -In most cases, you don't need this: +Nella maggior parte dei casi, non ne hai bisogno: -* **If the value you need can be computed entirely from the current props or other state, [remove that redundant state altogether.](/learn/choosing-the-state-structure#avoid-redundant-state)** If you're worried about recomputing too often, the [`useMemo` Hook](/reference/react/useMemo) can help. -* If you want to reset the entire component tree's state, [pass a different `key` to your component.](#resetting-state-with-a-key) -* If you can, update all the relevant state in the event handlers. +* **Se il valore di cui hai bisogno può essere calcolato interamente dalle props correnti o da altro state, [rimuovi del tutto quello state ridondante.](/learn/choosing-the-state-structure#avoid-redundant-state)** Se temi di ricalcolare troppo spesso, l'[Hook `useMemo`](/reference/react/useMemo) può aiutare. +* Se vuoi reimpostare lo state dell'intero albero di componenti, [passa una `key` diversa al tuo componente.](#resetting-state-with-a-key) +* Se puoi, aggiorna tutto lo state rilevante nei gestori di eventi. -In the rare case that none of these apply, there is a pattern you can use to update state based on the values that have been rendered so far, by calling a `set` function while your component is rendering. +Nel raro caso in cui nessuna di queste opzioni si applichi, c'è un pattern che puoi usare per aggiornare lo state in base ai valori renderizzati finora, chiamando una funzione `set` mentre il tuo componente è in renderizzazione. -Here's an example. This `CountLabel` component displays the `count` prop passed to it: +Ecco un esempio. Questo componente `CountLabel` visualizza la prop `count` che gli viene passata: ```js src/CountLabel.js export default function CountLabel({ count }) { @@ -1091,7 +1098,7 @@ export default function CountLabel({ count }) { } ``` -Say you want to show whether the counter has *increased or decreased* since the last change. The `count` prop doesn't tell you this -- you need to keep track of its previous value. Add the `prevCount` state variable to track it. Add another state variable called `trend` to hold whether the count has increased or decreased. Compare `prevCount` with `count`, and if they're not equal, update both `prevCount` and `trend`. Now you can show both the current count prop and *how it has changed since the last render*. +Supponiamo che tu voglia mostrare se il contatore è *aumentato o diminuito* dall'ultimo cambiamento. La prop `count` non te lo dice — devi tenere traccia del suo valore precedente. Aggiungi la variabile di state `prevCount` per tracciarlo. Aggiungi un'altra variabile di state chiamata `trend` per contenere se il contatore è aumentato o diminuito. Confronta `prevCount` con `count` e, se non sono uguali, aggiorna sia `prevCount` che `trend`. Ora puoi mostrare sia la prop `count` corrente sia *come è cambiata dall'ultima renderizzazione*. @@ -1140,34 +1147,34 @@ button { margin-bottom: 10px; } -Note that if you call a `set` function while rendering, it must be inside a condition like `prevCount !== count`, and there must be a call like `setPrevCount(count)` inside of the condition. Otherwise, your component would re-render in a loop until it crashes. Also, you can only update the state of the *currently rendering* component like this. Calling the `set` function of *another* component during rendering is an error. Finally, your `set` call should still [update state without mutation](#updating-objects-and-arrays-in-state) -- this doesn't mean you can break other rules of [pure functions.](/learn/keeping-components-pure) +Nota che se chiami una funzione `set` durante la renderizzazione, deve essere all'interno di una condizione come `prevCount !== count`, e deve esserci una chiamata come `setPrevCount(count)` all'interno della condizione. Altrimenti, il tuo componente si ri-renderizzerebbe in un loop finché non crasha. Inoltre, puoi aggiornare lo state solo del componente *attualmente in renderizzazione* in questo modo. Chiamare la funzione `set` di *un altro* componente durante la renderizzazione è un errore. Infine, la tua chiamata a `set` dovrebbe comunque [aggiornare lo state senza mutazione](#updating-objects-and-arrays-in-state) — questo non significa che puoi infrangere le altre regole delle [funzioni pure.](/learn/keeping-components-pure) -This pattern can be hard to understand and is usually best avoided. However, it's better than updating state in an effect. When you call the `set` function during render, React will re-render that component immediately after your component exits with a `return` statement, and before rendering the children. This way, children don't need to render twice. The rest of your component function will still execute (and the result will be thrown away). If your condition is below all the Hook calls, you may add an early `return;` to restart rendering earlier. +Questo pattern può essere difficile da capire ed è di solito meglio evitarlo. Tuttavia, è meglio che aggiornare lo state in un Effetto. Quando chiami la funzione `set` durante la renderizzazione, React ri-renderizzerà quel componente immediatamente dopo che il tuo componente esce con un'istruzione `return`, e prima di renderizzare i figli. In questo modo, i figli non devono renderizzarsi due volte. Il resto della funzione del tuo componente verrà comunque eseguito (e il risultato verrà scartato). Se la tua condizione è sotto tutte le chiamate agli Hook, puoi aggiungere un `return;` anticipato per riavviare la renderizzazione prima. --- ## Troubleshooting {/*troubleshooting*/} -### I've updated the state, but logging gives me the old value {/*ive-updated-the-state-but-logging-gives-me-the-old-value*/} +### Ho aggiornato lo state, ma il log mi dà il vecchio valore {/*ive-updated-the-state-but-logging-gives-me-the-old-value*/} -Calling the `set` function **does not change state in the running code**: +Chiamare la funzione `set` **non cambia lo state nel codice in esecuzione**: ```js {4,5,8} function handleClick() { console.log(count); // 0 - setCount(count + 1); // Request a re-render with 1 - console.log(count); // Still 0! + setCount(count + 1); // Richiede una ri-renderizzazione con 1 + console.log(count); // Ancora 0! setTimeout(() => { - console.log(count); // Also 0! + console.log(count); // Anche 0! }, 5000); } ``` -This is because [states behaves like a snapshot.](/learn/state-as-a-snapshot) Updating state requests another render with the new state value, but does not affect the `count` JavaScript variable in your already-running event handler. +Questo perché [lo state si comporta come un'istantanea.](/learn/state-as-a-snapshot) Aggiornare lo state richiede un'altra renderizzazione con il nuovo valore di state, ma non influisce sulla variabile JavaScript `count` nel gestore di eventi già in esecuzione. -If you need to use the next state, you can save it in a variable before passing it to the `set` function: +Se devi usare il prossimo state, puoi salvarlo in una variabile prima di passarlo alla funzione `set`: ```js const nextCount = count + 1; @@ -1179,19 +1186,19 @@ console.log(nextCount); // 1 --- -### I've updated the state, but the screen doesn't update {/*ive-updated-the-state-but-the-screen-doesnt-update*/} +### Ho aggiornato lo state, ma lo schermo non si aggiorna {/*ive-updated-the-state-but-the-screen-doesnt-update*/} -React will **ignore your update if the next state is equal to the previous state,** as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. This usually happens when you change an object or an array in state directly: +React **ignorerà il tuo aggiornamento se il prossimo state è uguale allo state precedente,** come determinato da un confronto [`Object.is`](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Di solito succede quando modifichi direttamente un oggetto o un array nello state: ```js -obj.x = 10; // 🚩 Wrong: mutating existing object -setObj(obj); // 🚩 Doesn't do anything +obj.x = 10; // 🚩 Sbagliato: mutare un oggetto esistente +setObj(obj); // 🚩 Non fa nulla ``` -You mutated an existing `obj` object and passed it back to `setObj`, so React ignored the update. To fix this, you need to ensure that you're always [_replacing_ objects and arrays in state instead of _mutating_ them](#updating-objects-and-arrays-in-state): +Hai mutato un oggetto `obj` esistente e l'hai passato di nuovo a `setObj`, quindi React ha ignorato l'aggiornamento. Per correggere, devi assicurarti di [_sostituire_ sempre oggetti e array nello state anziché _mutarli_](#updating-objects-and-arrays-in-state): ```js -// ✅ Correct: creating a new object +// ✅ Corretto: creare un nuovo oggetto setObj({ ...obj, x: 10 @@ -1200,78 +1207,78 @@ setObj({ --- -### I'm getting an error: "Too many re-renders" {/*im-getting-an-error-too-many-re-renders*/} +### Ricevo un errore: "Too many re-renders" {/*im-getting-an-error-too-many-re-renders*/} -You might get an error that says: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Typically, this means that you're unconditionally setting state *during render*, so your component enters a loop: render, set state (which causes a render), render, set state (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler: +Potresti ricevere un errore che dice: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Di solito, significa che stai impostando incondizionatamente lo state *durante la renderizzazione*, quindi il tuo componente entra in un loop: renderizzazione, impostazione dello state (che causa una renderizzazione), renderizzazione, impostazione dello state (che causa una renderizzazione), e così via. Molto spesso, questo è causato da un errore nella specifica di un gestore di eventi: ```js {1-2} -// 🚩 Wrong: calls the handler during render +// 🚩 Sbagliato: chiama il gestore durante la renderizzazione return -// ✅ Correct: passes down the event handler +// ✅ Corretto: passa il gestore di eventi return -// ✅ Correct: passes down an inline function +// ✅ Corretto: passa una funzione inline return ``` -If you can't find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `set` function call responsible for the error. +Se non riesci a trovare la causa di questo errore, clicca sulla freccia accanto all'errore nella console e scorri lo stack JavaScript per trovare la specifica chiamata alla funzione `set` responsabile dell'errore. --- -### My initializer or updater function runs twice {/*my-initializer-or-updater-function-runs-twice*/} +### La mia funzione di inizializzazione o di aggiornamento dello state viene eseguita due volte {/*my-initializer-or-updater-function-runs-twice*/} -In [Strict Mode](/reference/react/StrictMode), React will call some of your functions twice instead of once: +In [Strict Mode](/reference/react/StrictMode), React chiamerà alcune delle tue funzioni due volte anziché una: ```js {2,5-6,11-12} function TodoList() { - // This component function will run twice for every render. + // Questa funzione del componente verrà eseguita due volte per ogni renderizzazione. const [todos, setTodos] = useState(() => { - // This initializer function will run twice during initialization. + // Questa funzione di inizializzazione verrà eseguita due volte durante l'inizializzazione. return createTodos(); }); function handleClick() { setTodos(prevTodos => { - // This updater function will run twice for every click. + // Questa funzione di aggiornamento dello state verrà eseguita due volte per ogni click. return [...prevTodos, createTodo()]; }); } // ... ``` -This is expected and shouldn't break your code. +Questo è previsto e non dovrebbe rompere il tuo codice. -This **development-only** behavior helps you [keep components pure.](/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and updater functions are pure, this shouldn't affect your logic. However, if they are accidentally impure, this helps you notice the mistakes. +Questo comportamento **solo in development** ti aiuta a [mantenere i componenti puri.](/learn/keeping-components-pure) React usa il risultato di una delle chiamate e ignora il risultato dell'altra chiamata. Finché il tuo componente, le funzioni di inizializzazione e di aggiornamento dello state sono pure, non dovrebbe influire sulla tua logica. Tuttavia, se sono accidentalmente impure, questo ti aiuta a notare gli errori. -For example, this impure updater function mutates an array in state: +Per esempio, questa funzione di aggiornamento dello state impura muta un array nello state: ```js {2,3} setTodos(prevTodos => { - // 🚩 Mistake: mutating state + // 🚩 Errore: mutare lo state prevTodos.push(createTodo()); }); ``` -Because React calls your updater function twice, you'll see the todo was added twice, so you'll know that there is a mistake. In this example, you can fix the mistake by [replacing the array instead of mutating it](#updating-objects-and-arrays-in-state): +Poiché React chiama la tua funzione di aggiornamento dello state due volte, vedrai che il todo è stato aggiunto due volte, quindi saprai che c'è un errore. In questo esempio, puoi correggere l'errore [sostituendo l'array anziché mutarlo](#updating-objects-and-arrays-in-state): ```js {2,3} setTodos(prevTodos => { - // ✅ Correct: replacing with new state + // ✅ Corretto: sostituire con un nuovo state return [...prevTodos, createTodo()]; }); ``` -Now that this updater function is pure, calling it an extra time doesn't make a difference in behavior. This is why React calling it twice helps you find mistakes. **Only component, initializer, and updater functions need to be pure.** Event handlers don't need to be pure, so React will never call your event handlers twice. +Ora che questa funzione di aggiornamento dello state è pura, chiamarla una volta in più non fa differenza nel comportamento. Ecco perché React chiamarla due volte ti aiuta a trovare gli errori. **Solo le funzioni del componente, di inizializzazione e di aggiornamento dello state devono essere pure.** I gestori di eventi non devono essere puri, quindi React non chiamerà mai i tuoi gestori di eventi due volte. -Read [keeping components pure](/learn/keeping-components-pure) to learn more. +Leggi [mantenere i componenti puri](/learn/keeping-components-pure) per saperne di più. --- -### I'm trying to set state to a function, but it gets called instead {/*im-trying-to-set-state-to-a-function-but-it-gets-called-instead*/} +### Sto cercando di impostare lo state su una funzione, ma viene chiamata {/*im-trying-to-set-state-to-a-function-but-it-gets-called-instead*/} -You can't put a function into state like this: +Non puoi mettere una funzione nello state così: ```js const [fn, setFn] = useState(someFunction); @@ -1281,7 +1288,7 @@ function handleClick() { } ``` -Because you're passing a function, React assumes that `someFunction` is an [initializer function](#avoiding-recreating-the-initial-state), and that `someOtherFunction` is an [updater function](#updating-state-based-on-the-previous-state), so it tries to call them and store the result. To actually *store* a function, you have to put `() =>` before them in both cases. Then React will store the functions you pass. +Poiché stai passando una funzione, React assume che `someFunction` sia una [funzione di inizializzazione](#avoiding-recreating-the-initial-state) e che `someOtherFunction` sia una [funzione di aggiornamento dello state](#updating-state-based-on-the-previous-state), quindi prova a chiamarle e memorizzare il risultato. Per *memorizzare* effettivamente una funzione, devi mettere `() =>` prima di entrambe. Allora React memorizzerà le funzioni che passi. ```js {1,4} const [fn, setFn] = useState(() => someFunction);