From 2d07f248be07b4e3d704d3313398f88581255f84 Mon Sep 17 00:00:00 2001 From: Alessandro De Blasis Date: Tue, 15 Sep 2026 12:05:12 +0300 Subject: [PATCH 1/2] translate(learn): preserving-and-resetting-state Signed-off-by: Alessandro De Blasis --- .../learn/preserving-and-resetting-state.md | 365 +++++++++--------- src/sidebarLearn.json | 2 +- 2 files changed, 187 insertions(+), 180 deletions(-) diff --git a/src/content/learn/preserving-and-resetting-state.md b/src/content/learn/preserving-and-resetting-state.md index 685f63ef4..b42463995 100644 --- a/src/content/learn/preserving-and-resetting-state.md +++ b/src/content/learn/preserving-and-resetting-state.md @@ -1,28 +1,35 @@ --- -title: Preserving and Resetting State +title: Preservare e Reimpostare lo State +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/learn/preserving-and-resetting-state.md). + + + -State is isolated between components. React keeps track of which state belongs to which component based on their place in the UI tree. You can control when to preserve state and when to reset it between re-renders. +Lo state è isolato tra i componenti. React tiene traccia di quale state appartiene a quale componente in base alla sua posizione nell'albero dell'UI. Puoi controllare quando preservare lo state e quando reimpostarlo tra le ri-renderizzazioni. -* When React chooses to preserve or reset the state -* How to force React to reset component's state -* How keys and types affect whether the state is preserved +* Quando React sceglie di preservare o reimpostare lo state +* Come forzare React a reimpostare lo state di un componente +* Come le key e i tipi influenzano se lo state viene preservato -## State is tied to a position in the render tree {/*state-is-tied-to-a-position-in-the-tree*/} +## Lo state è legato a una posizione nell'albero di renderizzazione {/*state-is-tied-to-a-position-in-the-tree*/} -React builds [render trees](learn/understanding-your-ui-as-a-tree#the-render-tree) for the component structure in your UI. +React costruisce [alberi di renderizzazione](/learn/understanding-your-ui-as-a-tree#the-render-tree) per la struttura dei componenti nella tua UI. -When you give a component state, you might think the state "lives" inside the component. But the state is actually held inside React. React associates each piece of state it's holding with the correct component by where that component sits in the render tree. +Quando dai state a un componente, potresti pensare che lo state "viva" dentro il componente. Ma lo state è in realtà conservato dentro React. React associa ogni pezzo di state che conserva al componente corretto in base a dove quel componente si trova nell'albero di renderizzazione. -Here, there is only one `` JSX tag, but it's rendered at two different positions: +Qui c'è un solo tag JSX ``, ma viene renderizzato in due posizioni diverse: @@ -56,7 +63,7 @@ function Counter() { >

{score}

); @@ -86,23 +93,23 @@ label {
-Here's how these look as a tree: +Ecco come appaiono come albero: - + -React tree +Albero React -**These are two separate counters because each is rendered at its own position in the tree.** You don't usually have to think about these positions to use React, but it can be useful to understand how it works. +**Questi sono due contatori separati perché ciascuno è renderizzato nella propria posizione nell'albero.** Di solito non devi pensare a queste posizioni per usare React, ma può essere utile capire come funziona. -In React, each component on the screen has fully isolated state. For example, if you render two `Counter` components side by side, each of them will get its own, independent, `score` and `hover` states. +In React, ogni componente sullo schermo ha uno state completamente isolato. Ad esempio, se renderizzi due componenti `Counter` affiancati, ciascuno avrà i propri state `score` e `hover` indipendenti. -Try clicking both counters and notice they don't affect each other: +Prova a cliccare entrambi i contatori e nota che non si influenzano a vicenda: @@ -135,7 +142,7 @@ function Counter() { >

{score}

); @@ -160,21 +167,21 @@ function Counter() {
-As you can see, when one counter is updated, only the state for that component is updated: +Come puoi vedere, quando un contatore viene aggiornato, viene aggiornato solo lo state di quel componente: - + -Updating state +Aggiornamento dello state -React will keep the state around for as long as you render the same component at the same position in the tree. To see this, increment both counters, then remove the second component by unchecking "Render the second counter" checkbox, and then add it back by ticking it again: +React manterrà lo state finché renderizzi lo stesso componente nella stessa posizione nell'albero. Per vederlo, incrementa entrambi i contatori, poi rimuovi il secondo componente deselezionando la checkbox "Renderizza il secondo contatore", e aggiungilo di nuovo selezionandola: @@ -195,7 +202,7 @@ export default function App() { setShowB(e.target.checked) }} /> - Render the second counter + Renderizza il secondo contatore ); @@ -218,7 +225,7 @@ function Counter() { >

{score}

); @@ -248,35 +255,35 @@ label {
-Notice how the moment you stop rendering the second counter, its state disappears completely. That's because when React removes a component, it destroys its state. +Nota come nel momento in cui smetti di renderizzare il secondo contatore, il suo state scompare completamente. Questo perché quando React rimuove un componente, ne distrugge lo state. - + -Deleting a component +Eliminazione di un componente -When you tick "Render the second counter", a second `Counter` and its state are initialized from scratch (`score = 0`) and added to the DOM. +Quando selezioni "Renderizza il secondo contatore", un secondo `Counter` e il suo state vengono inizializzati da zero (`score = 0`) e aggiunti al DOM. - + -Adding a component +Aggiunta di un componente -**React preserves a component's state for as long as it's being rendered at its position in the UI tree.** If it gets removed, or a different component gets rendered at the same position, React discards its state. +**React preserva lo state di un componente finché viene renderizzato nella sua posizione nell'albero dell'UI.** Se viene rimosso, o se un componente diverso viene renderizzato nella stessa posizione, React scarta il suo state. -## Same component at the same position preserves state {/*same-component-at-the-same-position-preserves-state*/} +## Lo stesso componente nella stessa posizione preserva lo state {/*same-component-at-the-same-position-preserves-state*/} -In this example, there are two different `` tags: +In questo esempio, ci sono due tag `` diversi: @@ -300,7 +307,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usa stile elegante ); @@ -326,7 +333,7 @@ function Counter({ isFancy }) { >

{score}

); @@ -361,24 +368,24 @@ label {
-When you tick or clear the checkbox, the counter state does not get reset. Whether `isFancy` is `true` or `false`, you always have a `` as the first child of the `div` returned from the root `App` component: +Quando selezioni o deselezioni la checkbox, lo state del contatore non viene reimpostato. Che `isFancy` sia `true` o `false`, hai sempre un `` come primo figlio del `div` restituito dal componente root `App`: - + -Updating the `App` state does not reset the `Counter` because `Counter` stays in the same position +Aggiornare lo state di `App` non reimposta `Counter` perché `Counter` resta nella stessa posizione -It's the same component at the same position, so from React's perspective, it's the same counter. +È lo stesso componente nella stessa posizione, quindi dal punto di vista di React, è lo stesso contatore. -Remember that **it's the position in the UI tree--not in the JSX markup--that matters to React!** This component has two `return` clauses with different `` JSX tags inside and outside the `if`: +Ricorda che **è la posizione nell'albero dell'UI — non nel markup JSX — che conta per React!** Questo componente ha due clausole `return` con tag JSX `` diversi dentro e fuori l'`if`: @@ -399,7 +406,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usa stile elegante ); @@ -415,7 +422,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usa stile elegante ); @@ -441,7 +448,7 @@ function Counter({ isFancy }) { >

{score}

); @@ -476,15 +483,15 @@ label {
-You might expect the state to reset when you tick checkbox, but it doesn't! This is because **both of these `` tags are rendered at the same position.** React doesn't know where you place the conditions in your function. All it "sees" is the tree you return. +Potresti aspettarti che lo state venga reimpostato quando selezioni la checkbox, ma non succede! Questo perché **entrambi questi tag `` sono renderizzati nella stessa posizione.** React non sa dove posizioni le condizioni nella tua funzione. Tutto ciò che "vede" è l'albero che restituisci. -In both cases, the `App` component returns a `
` with `` as a first child. To React, these two counters have the same "address": the first child of the first child of the root. This is how React matches them up between the previous and next renders, regardless of how you structure your logic. +In entrambi i casi, il componente `App` restituisce un `
` con `` come primo figlio. Per React, questi due contatori hanno lo stesso "indirizzo": il primo figlio del primo figlio della root. È così che React li abbina tra la renderizzazione precedente e quella successiva, indipendentemente da come strutturi la tua logica. -## Different components at the same position reset state {/*different-components-at-the-same-position-reset-state*/} +## Componenti diversi nella stessa posizione reimpostano lo state {/*different-components-at-the-same-position-reset-state*/} -In this example, ticking the checkbox will replace `` with a `

`: +In questo esempio, selezionare la checkbox sostituirà `` con un `

`: @@ -496,7 +503,7 @@ export default function App() { return (

{isPaused ? ( -

See you later!

+

A presto!

) : ( )} @@ -508,7 +515,7 @@ export default function App() { setIsPaused(e.target.checked) }} /> - Take a break + Fai una pausa
); @@ -531,7 +538,7 @@ function Counter() { >

{score}

); @@ -561,13 +568,13 @@ label { -Here, you switch between _different_ component types at the same position. Initially, the first child of the `
` contained a `Counter`. But when you swapped in a `p`, React removed the `Counter` from the UI tree and destroyed its state. +Qui, passi tra tipi di componente _diversi_ nella stessa posizione. Inizialmente, il primo figlio del `
` conteneva un `Counter`. Ma quando lo hai sostituito con un `p`, React ha rimosso il `Counter` dall'albero dell'UI e ha distrutto il suo state. - + -When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added +Quando `Counter` diventa `p`, il `Counter` viene eliminato e il `p` viene aggiunto @@ -575,15 +582,15 @@ When `Counter` changes to `p`, the `Counter` is deleted and the `p` is added - + -When switching back, the `p` is deleted and the `Counter` is added +Quando si torna indietro, il `p` viene eliminato e il `Counter` viene aggiunto -Also, **when you render a different component in the same position, it resets the state of its entire subtree.** To see how this works, increment the counter and then tick the checkbox: +Inoltre, **quando renderizzi un componente diverso nella stessa posizione, reimposta lo state dell'intero sottoalbero.** Per vedere come funziona, incrementa il contatore e poi seleziona la checkbox: @@ -611,7 +618,7 @@ export default function App() { setIsFancy(e.target.checked) }} /> - Use fancy styling + Usa stile elegante
); @@ -637,7 +644,7 @@ function Counter({ isFancy }) { >

{score}

); @@ -672,13 +679,13 @@ label { -The counter state gets reset when you click the checkbox. Although you render a `Counter`, the first child of the `div` changes from a `section` to a `div`. When the child `section` was removed from the DOM, the whole tree below it (including the `Counter` and its state) was destroyed as well. +Lo state del contatore viene reimpostato quando clicchi la checkbox. Anche se renderizzi un `Counter`, il primo figlio del `div` cambia da un `section` a un `div`. Quando il figlio `section` è stato rimosso dal DOM, l'intero albero sotto di esso (inclusi il `Counter` e il suo state) è stato distrutto. - + -When `section` changes to `div`, the `section` is deleted and the new `div` is added +Quando `section` diventa `div`, il `section` viene eliminato e il nuovo `div` viene aggiunto @@ -686,21 +693,21 @@ When `section` changes to `div`, the `section` is deleted and the new `div` is a - + -When switching back, the `div` is deleted and the new `section` is added +Quando si torna indietro, il `div` viene eliminato e il nuovo `section` viene aggiunto -As a rule of thumb, **if you want to preserve the state between re-renders, the structure of your tree needs to "match up"** from one render to another. If the structure is different, the state gets destroyed because React destroys state when it removes a component from the tree. +Come regola generale, **se vuoi preservare lo state tra le ri-renderizzazioni, la struttura del tuo albero deve "corrispondere"** da una renderizzazione all'altra. Se la struttura è diversa, lo state viene distrutto perché React distrugge lo state quando rimuove un componente dall'albero. -This is why you should not nest component function definitions. +Ecco perché non dovresti annidare definizioni di funzioni componente. -Here, the `MyTextField` component function is defined *inside* `MyComponent`: +Qui, la funzione componente `MyTextField` è definita *dentro* `MyComponent`: @@ -726,7 +733,7 @@ export default function MyComponent() { + }}>Cliccato {counter} volte ); } @@ -735,13 +742,13 @@ export default function MyComponent() { -Every time you click the button, the input state disappears! This is because a *different* `MyTextField` function is created for every render of `MyComponent`. You're rendering a *different* component in the same position, so React resets all state below. This leads to bugs and performance problems. To avoid this problem, **always declare component functions at the top level, and don't nest their definitions.** +Ogni volta che clicchi il pulsante, lo state dell'input scompare! Questo perché una funzione `MyTextField` *diversa* viene creata a ogni renderizzazione di `MyComponent`. Stai renderizzando un componente *diverso* nella stessa posizione, quindi React reimposta tutto lo state sotto. Questo porta a bug e problemi di performance. Per evitare questo problema, **dichiara sempre le funzioni componente al top level e non annidare le loro definizioni.** -## Resetting state at the same position {/*resetting-state-at-the-same-position*/} +## Reimpostare lo state nella stessa posizione {/*resetting-state-at-the-same-position*/} -By default, React preserves state of a component while it stays at the same position. Usually, this is exactly what you want, so it makes sense as the default behavior. But sometimes, you may want to reset a component's state. Consider this app that lets two players keep track of their scores during each turn: +Per impostazione predefinita, React preserva lo state di un componente finché resta nella stessa posizione. Di solito, è esattamente ciò che vuoi, quindi ha senso come comportamento predefinito. Ma a volte, potresti voler reimpostare lo state di un componente. Considera questa app che permette a due giocatori di tenere traccia dei propri punteggi durante ogni turno: @@ -760,7 +767,7 @@ export default function Scoreboard() {
); @@ -783,7 +790,7 @@ function Counter({ person }) { >

{person}'s score: {score}

); @@ -811,19 +818,19 @@ h1 { -Currently, when you change the player, the score is preserved. The two `Counter`s appear in the same position, so React sees them as *the same* `Counter` whose `person` prop has changed. +Attualmente, quando cambi giocatore, il punteggio viene preservato. I due `Counter` appaiono nella stessa posizione, quindi React li vede come *lo stesso* `Counter` la cui prop `person` è cambiata. -But conceptually, in this app they should be two separate counters. They might appear in the same place in the UI, but one is a counter for Taylor, and another is a counter for Sarah. +Ma concettualmente, in questa app dovrebbero essere due contatori separati. Potrebbero apparire nello stesso posto nell'UI, ma uno è un contatore per Taylor e l'altro è un contatore per Sarah. -There are two ways to reset state when switching between them: +Ci sono due modi per reimpostare lo state quando passi da uno all'altro: -1. Render components in different positions -2. Give each component an explicit identity with `key` +1. Renderizzare i componenti in posizioni diverse +2. Dare a ciascun componente un'identità esplicita con `key` -### Option 1: Rendering a component in different positions {/*option-1-rendering-a-component-in-different-positions*/} +### Opzione 1: Renderizzare un componente in posizioni diverse {/*option-1-rendering-a-component-in-different-positions*/} -If you want these two `Counter`s to be independent, you can render them in two different positions: +Se vuoi che questi due `Counter` siano indipendenti, puoi renderizzarli in due posizioni diverse: @@ -843,7 +850,7 @@ export default function Scoreboard() { ); @@ -866,7 +873,7 @@ function Counter({ person }) { >

{person}'s score: {score}

); @@ -894,42 +901,42 @@ h1 {
-* Initially, `isPlayerA` is `true`. So the first position contains `Counter` state, and the second one is empty. -* When you click the "Next player" button the first position clears but the second one now contains a `Counter`. +* Inizialmente, `isPlayerA` è `true`. Quindi la prima posizione contiene lo state di `Counter`, e la seconda è vuota. +* Quando clicchi il pulsante "Giocatore successivo", la prima posizione si svuota ma la seconda ora contiene un `Counter`. - + -Initial state +State iniziale - + -Clicking "next" +Clic su "successivo" - + -Clicking "next" again +Clic su "successivo" di nuovo -Each `Counter`'s state gets destroyed each time it's removed from the DOM. This is why they reset every time you click the button. +Lo state di ciascun `Counter` viene distrutto ogni volta che viene rimosso dal DOM. Ecco perché si reimpostano ogni volta che clicchi il pulsante. -This solution is convenient when you only have a few independent components rendered in the same place. In this example, you only have two, so it's not a hassle to render both separately in the JSX. +Questa soluzione è comoda quando hai solo pochi componenti indipendenti renderizzati nello stesso posto. In questo esempio, ne hai solo due, quindi non è un problema renderizzarli separatamente nel JSX. -### Option 2: Resetting state with a key {/*option-2-resetting-state-with-a-key*/} +### Opzione 2: Reimpostare lo state con una key {/*option-2-resetting-state-with-a-key*/} -There is also another, more generic, way to reset a component's state. +C'è anche un altro modo, più generico, per reimpostare lo state di un componente. -You might have seen `key`s when [rendering lists.](/learn/rendering-lists#keeping-list-items-in-order-with-key) Keys aren't just for lists! You can use keys to make React distinguish between any components. By default, React uses order within the parent ("first counter", "second counter") to discern between components. But keys let you tell React that this is not just a *first* counter, or a *second* counter, but a specific counter--for example, *Taylor's* counter. This way, React will know *Taylor's* counter wherever it appears in the tree! +Potresti aver visto le `key` quando [renderizzi liste.](/learn/rendering-lists#keeping-list-items-in-order-with-key) Le key non servono solo per le liste! Puoi usare le key per far distinguere a React qualsiasi componente. Per impostazione predefinita, React usa l'ordine all'interno del genitore ("primo contatore", "secondo contatore") per distinguere i componenti. Ma le key ti permettono di dire a React che questo non è solo un *primo* contatore, o un *secondo* contatore, ma un contatore specifico — ad esempio, il contatore di *Taylor*. In questo modo, React conoscerà il contatore di *Taylor* ovunque appaia nell'albero! -In this example, the two ``s don't share state even though they appear in the same place in JSX: +In questo esempio, i due `` non condividono lo state anche se appaiono nello stesso posto nel JSX: @@ -948,7 +955,7 @@ export default function Scoreboard() { ); @@ -971,7 +978,7 @@ function Counter({ person }) { >

{person}'s score: {score}

); @@ -999,7 +1006,7 @@ h1 {
-Switching between Taylor and Sarah does not preserve the state. This is because **you gave them different `key`s:** +Passare tra Taylor e Sarah non preserva lo state. Questo perché **hai dato loro `key` diverse:** ```js {isPlayerA ? ( @@ -1009,19 +1016,19 @@ Switching between Taylor and Sarah does not preserve the state. This is because )} ``` -Specifying a `key` tells React to use the `key` itself as part of the position, instead of their order within the parent. This is why, even though you render them in the same place in JSX, React sees them as two different counters, and so they will never share state. Every time a counter appears on the screen, its state is created. Every time it is removed, its state is destroyed. Toggling between them resets their state over and over. +Specificare una `key` dice a React di usare la `key` stessa come parte della posizione, invece del loro ordine all'interno del genitore. Ecco perché, anche se li renderizzi nello stesso posto nel JSX, React li vede come due contatori diversi, e quindi non condivideranno mai lo state. Ogni volta che un contatore appare sullo schermo, il suo state viene creato. Ogni volta che viene rimosso, il suo state viene distrutto. Alternare tra loro reimposta il loro state ogni volta. -Remember that keys are not globally unique. They only specify the position *within the parent*. +Ricorda che le key non sono univoche a livello globale. Specificano solo la posizione *all'interno del genitore*. -### Resetting a form with a key {/*resetting-a-form-with-a-key*/} +### Reimpostare un form con una key {/*resetting-a-form-with-a-key*/} -Resetting state with a key is particularly useful when dealing with forms. +Reimpostare lo state con una key è particolarmente utile quando si tratta di form. -In this chat app, the `` component contains the text input state: +In questa app di chat, il componente `` contiene lo state dell'input di testo: @@ -1084,11 +1091,11 @@ export default function Chat({ contact }) {