diff --git a/src/content/reference/react/createContext.md b/src/content/reference/react/createContext.md index e4e9bcf62..2645896fd 100644 --- a/src/content/reference/react/createContext.md +++ b/src/content/reference/react/createContext.md @@ -1,10 +1,17 @@ --- title: createContext +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/createContext.md). + + + -`createContext` lets you create a [context](/learn/passing-data-deeply-with-context) that components can provide or read. +`createContext` ti permette di creare un [context](/learn/passing-data-deeply-with-context) che i componenti possono fornire o leggere. ```js const SomeContext = createContext(defaultValue) @@ -20,7 +27,7 @@ const SomeContext = createContext(defaultValue) ### `createContext(defaultValue)` {/*createcontext*/} -Call `createContext` outside of any components to create a context. +Chiama `createContext` al di fuori di qualsiasi componente per creare un context. ```js import { createContext } from 'react'; @@ -28,27 +35,27 @@ import { createContext } from 'react'; const ThemeContext = createContext('light'); ``` -[See more examples below.](#usage) +[Vedi altri esempi sotto.](#usage) #### Parameters {/*parameters*/} -* `defaultValue`: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don't have any meaningful default value, specify `null`. The default value is meant as a "last resort" fallback. It is static and never changes over time. +* `defaultValue`: Il valore che vuoi che il context abbia quando non c'è un context provider corrispondente nell'albero sopra il componente che legge il context. Se non hai un valore predefinito significativo, specifica `null`. Il valore predefinito è pensato come fallback "d'ultima risorsa". È statico e non cambia mai nel tempo. #### Returns {/*returns*/} -`createContext` returns a context object. +`createContext` restituisce un oggetto context. -**The context object itself does not hold any information.** It represents _which_ context other components read or provide. Typically, you will use [`SomeContext`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/reference/react/useContext) in components below to read it. The context object has a few properties: +**L'oggetto context in sé non contiene alcuna informazione.** Rappresenta _quale_ context altri componenti leggono o forniscono. In genere, userai [`SomeContext`](#provider) nei componenti sopra per specificare il valore del context, e chiamerai [`useContext(SomeContext)`](/reference/react/useContext) nei componenti sotto per leggerlo. L'oggetto context ha alcune proprietà: -* `SomeContext` lets you provide the context value to components. -* `SomeContext.Consumer` is an alternative and rarely used way to read the context value. -* `SomeContext.Provider` is a legacy way to provide the context value before React 19. +* `SomeContext` ti permette di fornire il valore del context ai componenti. +* `SomeContext.Consumer` è un modo alternativo e raramente usato per leggere il valore del context. +* `SomeContext.Provider` è un modo legacy per fornire il valore del context prima di React 19. --- -### `SomeContext` Provider {/*provider*/} +### Provider di `SomeContext` {/*provider*/} -Wrap your components into a context provider to specify the value of this context for all components inside: +Avvolgi i tuoi componenti in un context provider per specificare il valore di questo context per tutti i componenti al suo interno: ```js function App() { @@ -64,25 +71,25 @@ function App() { -Starting in React 19, you can render `` as a provider. +A partire da React 19, puoi renderizzare `` come provider. -In older versions of React, use ``. +Nelle versioni precedenti di React, usa ``. #### Props {/*provider-props*/} -* `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/reference/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it. +* `value`: Il valore che vuoi passare a tutti i componenti che leggono questo context all'interno di questo provider, indipendentemente dalla profondità. Il valore del context può essere di qualsiasi tipo. Un componente che chiama [`useContext(SomeContext)`](/reference/react/useContext) all'interno del provider riceve il `value` del context provider corrispondente più interno sopra di esso. --- ### `SomeContext.Consumer` {/*consumer*/} -Before `useContext` existed, there was an older way to read context: +Prima che esistesse `useContext`, c'era un modo più vecchio per leggere il context: ```js function Button() { - // 🟡 Legacy way (not recommended) + // 🟡 Modo legacy (sconsigliato) return ( {theme => ( @@ -93,11 +100,11 @@ function Button() { } ``` -Although this older way still works, **newly written code should read context with [`useContext()`](/reference/react/useContext) instead:** +Anche se questo modo più vecchio funziona ancora, **il codice scritto di recente dovrebbe leggere il context con [`useContext()`](/reference/react/useContext) invece:** ```js function Button() { - // ✅ Recommended way + // ✅ Modo consigliato const theme = useContext(ThemeContext); return @@ -269,16 +276,16 @@ label { -To make your component re-render only when a _part_ of some context changes, split your component in two. Read what you need from the context in the outer component, and pass it down to a memoized child as a prop. +Per far ri-renderizzare il tuo componente solo quando cambia _una parte_ di un context, dividi il componente in due. Leggi ciò che ti serve dal context nel componente esterno, e passalo a un figlio memorizzato come prop. --- -### Minimizing props changes {/*minimizing-props-changes*/} +### Minimizzare i cambiamenti delle props {/*minimizing-props-changes*/} -When you use `memo`, your component re-renders whenever any prop is not *shallowly equal* to what it was previously. This means that React compares every prop in your component with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. Note that `Object.is(3, 3)` is `true`, but `Object.is({}, {})` is `false`. +Quando usi `memo`, il tuo componente viene ri-renderizzato ogni volta che una prop non è *superficialmente uguale* a quella precedente. Ciò significa che React confronta ogni prop del tuo componente con il suo valore precedente usando il confronto [`Object.is`](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Nota che `Object.is(3, 3)` è `true`, ma `Object.is({}, {})` è `false`. -To get the most out of `memo`, minimize the times that the props change. For example, if the prop is an object, prevent the parent component from re-creating that object every time by using [`useMemo`:](/reference/react/useMemo) +Per ottenere il massimo da `memo`, minimizza le volte in cui le props cambiano. Per esempio, se la prop è un oggetto, evita che il componente genitore ricrei quell'oggetto ogni volta usando [`useMemo`:](/reference/react/useMemo) ```js {5-8} function Page() { @@ -298,7 +305,7 @@ const Profile = memo(function Profile({ person }) { }); ``` -A better way to minimize props changes is to make sure the component accepts the minimum necessary information in its props. For example, it could accept individual values instead of a whole object: +Un modo migliore per minimizzare i cambiamenti delle props è assicurarsi che il componente accetti nelle props solo le informazioni minime necessarie. Per esempio, potrebbe accettare valori individuali invece di un intero oggetto: ```js {4,7} function Page() { @@ -312,7 +319,7 @@ const Profile = memo(function Profile({ name, age }) { }); ``` -Even individual values can sometimes be projected to ones that change less frequently. For example, here a component accepts a boolean indicating the presence of a value rather than the value itself: +Anche i valori individuali a volte possono essere proiettati su altri che cambiano meno frequentemente. Per esempio, qui un componente accetta un booleano che indica la presenza di un valore piuttosto che il valore stesso: ```js {3} function GroupsLanding({ person }) { @@ -325,13 +332,13 @@ const CallToAction = memo(function CallToAction({ hasGroups }) { }); ``` -When you need to pass a function to memoized component, either declare it outside your component so that it never changes, or [`useCallback`](/reference/react/useCallback#skipping-re-rendering-of-components) to cache its definition between re-renders. +Quando devi passare una funzione a un componente memorizzato, dichiara la funzione fuori dal tuo componente in modo che non cambi mai, oppure usa [`useCallback`](/reference/react/useCallback#skipping-re-rendering-of-components) per memorizzare la sua definizione tra le ri-renderizzazioni. --- -### Specifying a custom comparison function {/*specifying-a-custom-comparison-function*/} +### Specificare una funzione di confronto personalizzata {/*specifying-a-custom-comparison-function*/} -In rare cases it may be infeasible to minimize the props changes of a memoized component. In that case, you can provide a custom comparison function, which React will use to compare the old and new props instead of using shallow equality. This function is passed as a second argument to `memo`. It should return `true` only if the new props would result in the same output as the old props; otherwise it should return `false`. +In casi rari può essere impraticabile minimizzare i cambiamenti delle props di un componente memorizzato. In quel caso, puoi fornire una funzione di confronto personalizzata, che React userà per confrontare le props vecchie e nuove invece di usare l'uguaglianza superficiale. Questa funzione viene passata come secondo argomento a `memo`. Dovrebbe restituire `true` solo se le nuove props produrrebbero lo stesso output delle vecchie props; altrimenti dovrebbe restituire `false`. ```js {3} const Chart = memo(function Chart({ dataPoints }) { @@ -349,30 +356,30 @@ function arePropsEqual(oldProps, newProps) { } ``` -If you do this, use the Performance panel in your browser developer tools to make sure that your comparison function is actually faster than re-rendering the component. You might be surprised. +Se lo fai, usa il pannello Performance negli strumenti per sviluppatori del browser per assicurarti che la tua funzione di confronto sia effettivamente più veloce della ri-renderizzazione del componente. Potresti rimanere sorpreso. -When you do performance measurements, make sure that React is running in the production mode. +Quando fai misurazioni delle prestazioni, assicurati che React sia in esecuzione in modalità produzione. -If you provide a custom `arePropsEqual` implementation, **you must compare every prop, including functions.** Functions often [close over](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) the props and state of parent components. If you return `true` when `oldProps.onClick !== newProps.onClick`, your component will keep "seeing" the props and state from a previous render inside its `onClick` handler, leading to very confusing bugs. +Se fornisci un'implementazione personalizzata di `arePropsEqual`, **devi confrontare ogni prop, incluse le funzioni.** Le funzioni spesso [catturano](https://developer.mozilla.org/it/docs/Web/JavaScript/Closures) le props e lo state dei componenti genitori. Se restituisci `true` quando `oldProps.onClick !== newProps.onClick`, il tuo componente continuerà a "vedere" le props e lo state di una renderizzazione precedente dentro il suo gestore `onClick`, portando a bug molto confusi. -Avoid doing deep equality checks inside `arePropsEqual` unless you are 100% sure that the data structure you're working with has a known limited depth. **Deep equality checks can become incredibly slow** and can freeze your app for many seconds if someone changes the data structure later. +Evita di fare controlli di uguaglianza profonda dentro `arePropsEqual` a meno che non sia sicuro al 100% che la struttura dati su cui lavori abbia una profondità nota e limitata. **I controlli di uguaglianza profonda possono diventare incredibilmente lenti** e possono bloccare la tua app per molti secondi se qualcuno cambia la struttura dati in seguito. --- -### Do I still need React.memo if I use React Compiler? {/*react-compiler-memo*/} +### Ho ancora bisogno di React.memo se uso React Compiler? {/*react-compiler-memo*/} -When you enable [React Compiler](/learn/react-compiler), you typically don't need `React.memo` anymore. The compiler automatically optimizes component re-rendering for you. +Quando abiliti [React Compiler](/learn/react-compiler), di solito non hai più bisogno di `React.memo`. Il compiler ottimizza automaticamente la ri-renderizzazione dei componenti per te. -Here's how it works: +Ecco come funziona: -**Without React Compiler**, you need `React.memo` to prevent unnecessary re-renders: +**Senza React Compiler**, hai bisogno di `React.memo` per evitare ri-renderizzazioni non necessarie: ```js -// Parent re-renders every second +// Il genitore si ri-renderizza ogni secondo function Parent() { const [seconds, setSeconds] = useState(0); @@ -391,30 +398,30 @@ function Parent() { ); } -// Without memo, this re-renders every second even though props don't change +// Senza memo, questo si ri-renderizza ogni secondo anche se le props non cambiano const ExpensiveChild = memo(function ExpensiveChild({ name }) { console.log('ExpensiveChild rendered'); return
Hello, {name}!
; }); ``` -**With React Compiler enabled**, the same optimization happens automatically: +**Con React Compiler abilitato**, la stessa ottimizzazione avviene automaticamente: ```js -// No memo needed - compiler prevents re-renders automatically +// Nessun memo necessario: il compiler previene le ri-renderizzazioni automaticamente function ExpensiveChild({ name }) { console.log('ExpensiveChild rendered'); return
Hello, {name}!
; } ``` -Here's the key part of what the React Compiler generates: +Ecco la parte chiave di ciò che genera React Compiler: ```js {6-12} function Parent() { const $ = _c(7); const [seconds, setSeconds] = useState(0); - // ... other code ... + // ... altro codice ... let t3; if ($[4] === Symbol.for("react.memo_cache_sentinel")) { @@ -423,28 +430,28 @@ function Parent() { } else { t3 = $[4]; } - // ... return statement ... + // ... istruzione return ... } ``` -Notice the highlighted lines: The compiler wraps `` in a cache check. Since the `name` prop is always `"John"`, this JSX is created once and reused on every parent re-render. This is exactly what `React.memo` does - it prevents the child from re-rendering when its props haven't changed. +Nota le righe evidenziate: il compiler avvolge `` in un controllo della cache. Poiché la prop `name` è sempre `"John"`, questo JSX viene creato una volta e riusato a ogni ri-renderizzazione del genitore. Questo è esattamente ciò che fa `React.memo`: impedisce al figlio di ri-renderizzarsi quando le sue props non sono cambiate. -The React Compiler automatically: -1. Tracks that the `name` prop passed to `ExpensiveChild` hasn't changed -2. Reuses the previously created JSX for `` -3. Skips re-rendering `ExpensiveChild` entirely +React Compiler automaticamente: +1. Traccia che la prop `name` passata a `ExpensiveChild` non è cambiata +2. Riutilizza il JSX creato in precedenza per `` +3. Salta completamente la ri-renderizzazione di `ExpensiveChild` -This means **you can safely remove `React.memo` from your components when using React Compiler**. The compiler provides the same optimization automatically, making your code cleaner and easier to maintain. +Ciò significa che **puoi rimuovere `React.memo` dai tuoi componenti in sicurezza quando usi React Compiler**. Il compiler fornisce la stessa ottimizzazione automaticamente, rendendo il tuo codice più pulito e più facile da mantenere. -The compiler's optimization is actually more comprehensive than `React.memo`. It also memoizes intermediate values and expensive computations within your components, similar to combining `React.memo` with `useMemo` throughout your component tree. +L'ottimizzazione del compiler è in realtà più completa di `React.memo`. Memorizza anche valori intermedi e computazioni costose all'interno dei tuoi componenti, in modo simile a combinare `React.memo` con `useMemo` in tutto l'albero dei componenti. --- ## Troubleshooting {/*troubleshooting*/} -### My component re-renders when a prop is an object, array, or function {/*my-component-rerenders-when-a-prop-is-an-object-or-array*/} +### Il mio componente si ri-renderizza quando una prop è un oggetto, un array o una funzione {/*my-component-rerenders-when-a-prop-is-an-object-or-array*/} -React compares old and new props by shallow equality: that is, it considers whether each new prop is reference-equal to the old prop. If you create a new object or array each time the parent is re-rendered, even if the individual elements are each the same, React will still consider it to be changed. Similarly, if you create a new function when rendering the parent component, React will consider it to have changed even if the function has the same definition. To avoid this, [simplify props or memoize props in the parent component](#minimizing-props-changes). +React confronta le props vecchie e nuove per uguaglianza superficiale: cioè, considera se ogni nuova prop è reference-equal alla prop vecchia. Se crei un nuovo oggetto o array ogni volta che il genitore viene ri-renderizzato, anche se i singoli elementi sono gli stessi, React lo considererà comunque cambiato. Allo stesso modo, se crei una nuova funzione quando renderizzi il componente genitore, React la considererà cambiata anche se la funzione ha la stessa definizione. Per evitare questo, [semplifica le props o memorizza le props nel componente genitore](#minimizing-props-changes). diff --git a/src/content/reference/react/startTransition.md b/src/content/reference/react/startTransition.md index 1da920d5e..c2388180a 100644 --- a/src/content/reference/react/startTransition.md +++ b/src/content/reference/react/startTransition.md @@ -1,10 +1,17 @@ --- title: startTransition +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/startTransition.md). + + + -`startTransition` lets you render a part of the UI in the background. +`startTransition` ti permette di renderizzare una parte dell'UI in background. ```js startTransition(action) @@ -20,7 +27,7 @@ startTransition(action) ### `startTransition(action)` {/*starttransition*/} -The `startTransition` function lets you mark a state update as a Transition. +La funzione `startTransition` ti permette di contrassegnare un aggiornamento di state come una Transizione. ```js {7,9} import { startTransition } from 'react'; @@ -37,39 +44,39 @@ function TabContainer() { } ``` -[See more examples below.](#usage) +[Vedi altri esempi sotto.](#usage) #### Parameters {/*parameters*/} -* `action`: A function that updates some state by calling one or more [`set` functions](/reference/react/useState#setstate). React calls `action` immediately with no parameters and marks all state updates scheduled synchronously during the `action` function call as Transitions. Any async calls awaited in the `action` will be included in the transition, but currently require wrapping any `set` functions after the `await` in an additional `startTransition` (see [Troubleshooting](/reference/react/useTransition#react-doesnt-treat-my-state-update-after-await-as-a-transition)). State updates marked as Transitions will be [non-blocking](#marking-a-state-update-as-a-non-blocking-transition) and [will not display unwanted loading indicators.](/reference/react/useTransition#preventing-unwanted-loading-indicators). +* `action`: Una funzione che aggiorna dello state chiamando una o più [`set` functions](/reference/react/useState#setstate). React chiama `action` immediatamente senza parametri e contrassegna come Transizioni tutti gli aggiornamenti di state pianificati in modo sincrono durante la chiamata alla funzione `action`. Qualsiasi chiamata async attesa con `await` in `action` sarà inclusa nella Transizione, ma attualmente richiede di avvolgere qualsiasi `set` function dopo `await` in un ulteriore `startTransition` (vedi [Troubleshooting](/reference/react/useTransition#react-doesnt-treat-my-state-update-after-await-as-a-transition)). Gli aggiornamenti di state contrassegnati come Transizioni saranno [non bloccanti](#marking-a-state-update-as-a-non-blocking-transition) e [non mostreranno indicatori di caricamento indesiderati.](/reference/react/useTransition#preventing-unwanted-loading-indicators) #### Returns {/*returns*/} -`startTransition` does not return anything. +`startTransition` non restituisce nulla. #### Caveats {/*caveats*/} -* `startTransition` does not provide a way to track whether a Transition is pending. To show a pending indicator while the Transition is ongoing, you need [`useTransition`](/reference/react/useTransition) instead. +* `startTransition` non fornisce un modo per tracciare se una Transizione è in corso. Per mostrare un indicatore di pending mentre la Transizione è in corso, hai bisogno di [`useTransition`](/reference/react/useTransition) al suo posto. -* You can wrap an update into a Transition only if you have access to the `set` function of that state. If you want to start a Transition in response to some prop or a custom Hook return value, try [`useDeferredValue`](/reference/react/useDeferredValue) instead. +* Puoi avvolgere un aggiornamento in una Transizione solo se hai accesso alla `set` function di quello state. Se vuoi avviare una Transizione in risposta a una prop o a un valore di un custom Hook, prova [`useDeferredValue`](/reference/react/useDeferredValue). -* The function you pass to `startTransition` is called immediately, marking all state updates that happen while it executes as Transitions. If you try to perform state updates in a `setTimeout`, for example, they won't be marked as Transitions. +* La funzione che passi a `startTransition` viene chiamata immediatamente, contrassegnando come Transizioni tutti gli aggiornamenti di state che avvengono mentre viene eseguita. Se provi a eseguire aggiornamenti di state in un `setTimeout`, per esempio, non saranno contrassegnati come Transizioni. -* You must wrap any state updates after any async requests in another `startTransition` to mark them as Transitions. This is a known limitation that we will fix in the future (see [Troubleshooting](/reference/react/useTransition#react-doesnt-treat-my-state-update-after-await-as-a-transition)). +* Devi avvolgere qualsiasi aggiornamento di state dopo richieste async in un altro `startTransition` per contrassegnarli come Transizioni. Questa è una limitazione nota che correggeremo in futuro (vedi [Troubleshooting](/reference/react/useTransition#react-doesnt-treat-my-state-update-after-await-as-a-transition)). -* A state update marked as a Transition will be interrupted by other state updates. For example, if you update a chart component inside a Transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input state update. +* Un aggiornamento di state contrassegnato come Transizione verrà interrotto da altri aggiornamenti di state. Per esempio, se aggiorni un componente grafico all'interno di una Transizione, ma poi inizi a digitare in un input mentre il grafico è nel mezzo di una ri-renderizzazione, React riavvierà il lavoro di renderizzazione sul componente grafico dopo aver gestito l'aggiornamento dell'input. -* Transition updates can't be used to control text inputs. +* Gli aggiornamenti Transizione non possono essere usati per controllare input di testo. -* If there are multiple ongoing Transitions, React currently batches them together. This is a limitation that may be removed in a future release. +* Se ci sono più Transizioni in corso, React attualmente le raggruppa insieme. Questa è una limitazione che potrebbe essere rimossa in una release futura. --- ## Usage {/*usage*/} -### Marking a state update as a non-blocking Transition {/*marking-a-state-update-as-a-non-blocking-transition*/} +### Contrassegnare un aggiornamento di state come Transizione non bloccante {/*marking-a-state-update-as-a-non-blocking-transition*/} -You can mark a state update as a *Transition* by wrapping it in a `startTransition` call: +Puoi contrassegnare un aggiornamento di state come una *Transizione* avvolgendolo in una chiamata a `startTransition`: ```js {7,9} import { startTransition } from 'react'; @@ -86,14 +93,14 @@ function TabContainer() { } ``` -Transitions let you keep the user interface updates responsive even on slow devices. +Le Transizioni ti permettono di mantenere reattivi gli aggiornamenti dell'interfaccia utente anche su dispositivi lenti. -With a Transition, your UI stays responsive in the middle of a re-render. For example, if the user clicks a tab but then change their mind and click another tab, they can do that without waiting for the first re-render to finish. +Con una Transizione, la tua UI resta reattiva nel mezzo di una ri-renderizzazione. Per esempio, se l'utente clicca una tab ma poi cambia idea e clicca un'altra tab, può farlo senza attendere che la prima ri-renderizzazione sia completata. -`startTransition` is very similar to [`useTransition`](/reference/react/useTransition), except that it does not provide the `isPending` flag to track whether a Transition is ongoing. The standalone function is also not associated with a component, so if the function passed to it throws an error or returns a rejected Promise, React reports the error with [`reportError`](https://developer.mozilla.org/en-US/docs/Web/API/Window/reportError). You can call `startTransition` when `useTransition` is not available. For example, `startTransition` works outside components, such as from a data library. +`startTransition` è molto simile a [`useTransition`](/reference/react/useTransition), tranne per il fatto che non fornisce il flag `isPending` per tracciare se una Transizione è in corso. La funzione standalone non è inoltre associata a un componente, quindi se la funzione passata lancia un errore o restituisce una Promise rifiutata, React segnala l'errore con [`reportError`](https://developer.mozilla.org/it/docs/Web/API/Window/reportError). Puoi chiamare `startTransition` quando `useTransition` non è disponibile. Per esempio, `startTransition` funziona fuori dai componenti, ad esempio da una libreria dati. -[Learn about Transitions and see examples on the `useTransition` page.](/reference/react/useTransition) +[Scopri di più sulle Transizioni e vedi esempi nella pagina `useTransition`.](/reference/react/useTransition)