diff --git a/GLOSSARY.md b/GLOSSARY.md index 9f2a41104..6f0969ca2 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -27,6 +27,10 @@ Glossary of the translations of technical and React-specific terms. - strict mode - web components - build steps +- wrapper +- provider +- consumer +- reducer # Common Translations diff --git a/content/docs/hooks-intro.md b/content/docs/hooks-intro.md index c5b6c8a4f..bda534549 100644 --- a/content/docs/hooks-intro.md +++ b/content/docs/hooks-intro.md @@ -5,106 +5,106 @@ permalink: docs/hooks-intro.html next: hooks-overview.html --- -*Hooks* are a new addition in React 16.8. They let you use state and other React features without writing a class. +Gli *Hooks* sono stati aggiunti in React 16.8. Ti permettono di utilizzare `state` ed altre funzioni di React senza dover scrivere una classe. ```js{4,5} import React, { useState } from 'react'; -function Example() { - // Declare a new state variable, which we'll call "count" - const [count, setCount] = useState(0); +function Esempio() { + // Dichiara una nuova variable di stato, che chiameremo "contatore" + const [contatore, setContatore] = useState(0); return (
-

You clicked {count} times

-
); } ``` -This new function `useState` is the first "Hook" we'll learn about, but this example is just a teaser. Don't worry if it doesn't make sense yet! +Questa nuova funzione `useState` è il primo "Hook" che impareremo, l'esempio appena visto è solo un assaggio. Non preoccuparti se ti pare non abbia molto senso per il momento! -**You can start learning Hooks [on the next page](/docs/hooks-overview.html).** On this page, we'll continue by explaining why we're adding Hooks to React and how they can help you write great applications. +**Puoi incominciare a saperne di più riguardo agli Hooks [nella pagina successiva](/docs/hooks-overview.html).** In questa pagina, continueremo a spiegare perché abbiamo introdotto gli Hooks in React e come possono aiutarti a sviluppare ottime applicazioni. ->Note +>Nota > ->React 16.8.0 is the first release to support Hooks. When upgrading, don't forget to update all packages, including React DOM. React Native will support Hooks in the next stable release. +>React 16.8.0 è la prima versione che supporta gli Hooks. Durante l'upgrade, non dimenticare di aggiornare tutti i pacchetti, incluso React DOM. React Native supporterà gli Hooks nella prossima release stabile. -## Video Introduction {#video-introduction} +## Introduzione Video {#video-introduction} -At React Conf 2018, Sophie Alpert and Dan Abramov introduced Hooks, followed by Ryan Florence demonstrating how to refactor an application to use them. Watch the video here: +Durante React Conf 2018, Sophie Alpert e Dan Abramov hanno introdotto gli Hooks, seguiti da Ryan Florence che ha dimostrato come rifattorizzare una applicazione utilizzandoli. Eccoti il video:
-## No Breaking Changes {#no-breaking-changes} +## Retrocompatibili {#no-breaking-changes} -Before we continue, note that Hooks are: +Prima di continuare, ricorda che gli Hooks sono: -* **Completely opt-in.** You can try Hooks in a few components without rewriting any existing code. But you don't have to learn or use Hooks right now if you don't want to. -* **100% backwards-compatible.** Hooks don't contain any breaking changes. -* **Available now.** Hooks are now available with the release of v16.8.0. +* **Completamente facoltativi.** Puoi provare ad usare gli Hooks in pochi componenti senza dover riscrivere alcun codice esistente. Non devi per forza imparare o utilizzare gli Hooks adesso se non ti va. +* **100% retrocompatibili.** Gli Hooks non contengono alcun cambiamento che possa rompere funzionalità esistenti. +* **Disponibili ora.** Gli Hooks sono disponibili a partire dalla release v16.8.0. -**There are no plans to remove classes from React.** You can read more about the gradual adoption strategy for Hooks in the [bottom section](#gradual-adoption-strategy) of this page. +**Non esiste alcun piano per la rimozione delle classi da React.** Puoi leggere di più riguardo alla strategia di adozione graduale degli Hooks nella [sezione in basso](#gradual-adoption-strategy) in questa pagina. -**Hooks don't replace your knowledge of React concepts.** Instead, Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle. As we will show later, Hooks also offer a new powerful way to combine them. +**Gli Hooks non cambiano la tua conoscenza dei concetti di React.** Invece, gli Hooks offrono un accesso più diretto alle API dei concetti React che conosci già: props, state, context, refs, e lifecycle. Come mostreremo di seguito, gli Hooks offrono anche un nuovo potente modo per combinarli. -**If you just want to start learning Hooks, feel free to [jump directly to the next page!](/docs/hooks-overview.html)** You can also keep reading this page to learn more about why we're adding Hooks, and how we're going to start using them without rewriting our applications. +**Se ti interessa soltanto imparare gli Hooks, puoi [passare direttamente all pagina successiva!](/docs/hooks-overview.html)** Continua a leggere se invece vuoi saperne di più riguardo alle motivazioni dietro l'introduzione degli Hooks, oltre a capire come possiamo cominciare ad utilizzarli senza dover riscrivere le nostre applicazioni. -## Motivation {#motivation} +## Motivazioni {#motivation} -Hooks solve a wide variety of seemingly unconnected problems in React that we've encountered over five years of writing and maintaining tens of thousands of components. Whether you're learning React, use it daily, or even prefer a different library with a similar component model, you might recognize some of these problems. +Gli Hooks risolvono un'ampia varietà di problemi che sembrano disconnessi tra loro in React. Problemi che abbiamo incontrato in oltre cinque anni di scrittura e manutenzione di decine di migliaia di componenti. Se stai imparando React, se lo usi quotidianamente o anche se preferisci una libreria diversa che ha un modello simile basato sui componenti, riconoscerai alcuni di questi problemi. -### It's hard to reuse stateful logic between components {#its-hard-to-reuse-stateful-logic-between-components} +### È difficile riutilizzare logica dipendente dallo stato in componenti diversi {#its-hard-to-reuse-stateful-logic-between-components} -React doesn't offer a way to "attach" reusable behavior to a component (for example, connecting it to a store). If you've worked with React for a while, you may be familiar with patterns like [render props](/docs/render-props.html) and [higher-order components](/docs/higher-order-components.html) that try to solve this. But these patterns require you to restructure your components when you use them, which can be cumbersome and make code harder to follow. If you look at a typical React application in React DevTools, you will likely find a "wrapper hell" of components surrounded by layers of providers, consumers, higher-order components, render props, and other abstractions. While we could [filter them out in DevTools](https://github.com/facebook/react-devtools/pull/503), this points to a deeper underlying problem: React needs a better primitive for sharing stateful logic. +React non offre un modo per "collegare" comportamenti riutilizzabili ad un componente (per esempio, connetterlo ad uno store). Se hai acquisito un po' di esperienza in React, sarai a conoscenza di concetti come [render props](/docs/render-props.html) e [componenti di ordine superiore](/docs/higher-order-components.html) che provano a risolvere questo problema. Tuttavia, questi patterns ti richiedono di ristrutturare i tuoi componenti quando vuoi utilizzarli, il che può essere difficile oltre a rendere il codice più difficile da seguire. Se osservi una tipica applicazione React usando React DevTools, noterai molto probabilmente un "wrapper hell" di componenti circondato da livelli di providers, consumers, componenti di ordine superiore, render props, ed altre astrazioni. Anche se possiamo [filtrarli in DevTools](https://github.com/facebook/react-devtools/pull/503), il problema principale resta: React ha bisogno di una migliore primitiva per condividere logica basata sullo stato (stateful). -With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. **Hooks allow you to reuse stateful logic without changing your component hierarchy.** This makes it easy to share Hooks among many components or with the community. +Con gli Hooks, puoi estrarre logica stateful da un componente così da renderla testabile in modo indipendente e riutilizzabile. **Gli Hooks ti permettono di riutilizzare logica stateful senza dover cambiare la tua gerarchia dei componenti.** Ciò rende facile la condivisione degli Hooks tra vari componenti o con la comunità. -We'll discuss this more in [Building Your Own Hooks](/docs/hooks-custom.html). +Ne discuteremo più in dettaglio nella sezione [Hooks Personalizzati](/docs/hooks-custom.html). -### Complex components become hard to understand {#complex-components-become-hard-to-understand} +### Componenti complessi diventano difficili da capire {#complex-components-become-hard-to-understand} -We've often had to maintain components that started out simple but grew into an unmanageable mess of stateful logic and side effects. Each lifecycle method often contains a mix of unrelated logic. For example, components might perform some data fetching in `componentDidMount` and `componentDidUpdate`. However, the same `componentDidMount` method might also contain some unrelated logic that sets up event listeners, with cleanup performed in `componentWillUnmount`. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies. +Ci siamo ritrovati più volte a dover mantenere componenti che sono passati dall'essere semplici fino a crescere in un groviglio di logica stateful ed effetti collaterali. Ogni metodo di lifecycle spesso contiene un mix di logica non correlata. Per esempio, i componenti potrebbero richiamare dati da qualche API in `componentDidMount` e `componentDidUpdate`. Comunque, lo stesso metodo `componentDidMount` può contenere anche logica per l'impostazione di event listeners, con le relative operazioni di pulizia eseguite in `componentWillUnmount`. Parti di codice correlate e che generalmente cambiano allo stesso tempo finiscono per essere divise perchè abbiamo codice completamente non correlato all'interno dello stesso metodo. Ciò rende troppo semplice l'introduzione di bugs ed inconsistenze. -In many cases it's not possible to break these components into smaller ones because the stateful logic is all over the place. It's also difficult to test them. This is one of the reasons many people prefer to combine React with a separate state management library. However, that often introduces too much abstraction, requires you to jump between different files, and makes reusing components more difficult. +In molti casi non è possibile suddividere questi componenti in altri più piccoli in quanto la logica stateful è dappertutto. È difficile anche testare questi componenti. Ecco perchè molti preferiscono utilizzare una libreria di gestione dello stato separata. Comunque, ciò spesso introduce troppa astrazione, richiede di saltare da un file all'altro frequentemente e rende la riutilizzazione dei componenti più difficile. -To solve this, **Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data)**, rather than forcing a split based on lifecycle methods. You may also opt into managing the component's local state with a reducer to make it more predictable. +Per risolvere questo problema, **gli Hooks ti permettono di dividere un componente in funzioni più piccole basate sui pezzi che sono correlati (quali una sottoscrizione ad un particolare evento o la richiesta di dati)**, piuttosto che forzare una suddivisione basata sui metodi di lifecycle. Puoi anche decidere di gestire lo stato del tuo componente con un reducer per renderlo più prevedibile. -We'll discuss this more in [Using the Effect Hook](/docs/hooks-effect.html#tip-use-multiple-effects-to-separate-concerns). +Ne parleremo più in dettaglio nella sezione [Usare l'Hook Effect](/docs/hooks-effect.html#tip-use-multiple-effects-to-separate-concerns). -### Classes confuse both people and machines {#classes-confuse-both-people-and-machines} +### Le classi confondono sia le persone che le macchine {#classes-confuse-both-people-and-machines} -In addition to making code reuse and code organization more difficult, we've found that classes can be a large barrier to learning React. You have to understand how `this` works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable [syntax proposals](https://babeljs.io/docs/en/babel-plugin-transform-class-properties/), the code is very verbose. People can understand props, state, and top-down data flow perfectly well but still struggle with classes. The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers. +Oltre a rendere il riutilizzo del codice e la sua organizzazione più difficile, abbiamo notato che le classi costituiscono una grande barriera per l'apprendimento di React. Devi sapere come `this` funziona in JavaScript, il che è molto diverso da come funziona nella maggioranza dei linguaggi. Senza l'utilizzo di [proposte di sintassi](https://babeljs.io/docs/en/babel-plugin-transform-class-properties/) ancora instabili, il codice è molto verboso. Le persone possono capire perfettamente le props, lo state ed il flusso dati top-down, ma ritrovarsi ad avere difficoltà con le classi. La distinzione tra funzioni e componenti classe in React e quando usare l'una o l'altra alternativa causa spesso disaccordi anche tra gli sviluppatori React più esperti. -Additionally, React has been out for about five years, and we want to make sure it stays relevant in the next five years. As [Svelte](https://svelte.dev/), [Angular](https://angular.io/), [Glimmer](https://glimmerjs.com/), and others show, [ahead-of-time compilation](https://en.wikipedia.org/wiki/Ahead-of-time_compilation) of components has a lot of future potential. Especially if it's not limited to templates. Recently, we've been experimenting with [component folding](https://github.com/facebook/react/issues/7323) using [Prepack](https://prepack.io/), and we've seen promising early results. However, we found that class components can encourage unintentional patterns that make these optimizations fall back to a slower path. Classes present issues for today's tools, too. For example, classes don't minify very well, and they make hot reloading flaky and unreliable. We want to present an API that makes it more likely for code to stay on the optimizable path. +Inoltre, React è in uso da circa cinque anni e vogliamo fare in modo che resti rilevante anche per i prossimi cinque anni. Così come [Svelte](https://svelte.dev/), [Angular](https://angular.io/), [Glimmer](https://glimmerjs.com/), ed altri dimostrano, [la compilazione ahead-of-time](https://en.wikipedia.org/wiki/Ahead-of-time_compilation) dei componenti ha molto potenziale. Specialmente se non è limitata ai templates. Recentemente, abbiamo sperimentato con il [component folding](https://github.com/facebook/react/issues/7323) utilizzando [Prepack](https://prepack.io/) ed abbiamo ottenuto dei risultati preliminari molto promettenti. Comunque, abbiamo trovato che i componenti classe possono incoraggiare l'uso di patterns non intenzionali che possono invalidare queste ottimizzazioni facendole ricadere su percorsi più lenti. Le classi presentano problemi anche con gli strumenti ad oggi disponibili. Per esempio, non vengono minificate molto bene e rendono l'hot reloading ("caricamento a caldo") inaffidabile. Vogliamo presentare una API che può mantenere il codice sul percorso ottimizzabile. -To solve these problems, **Hooks let you use more of React's features without classes.** Conceptually, React components have always been closer to functions. Hooks embrace functions, but without sacrificing the practical spirit of React. Hooks provide access to imperative escape hatches and don't require you to learn complex functional or reactive programming techniques. +Per risolvere questi problemi, **gli Hooks ti permettono di utilizzare più funzioni di React senza dover ricorrere alle classi.** Concettualmente, i componenti React sono sempre stati più vicini alle funzioni. Gli Hooks abbracciano le funzioni, senza però sacrificare lo spirito pratico di React. Gli Hooks offrono accesso a vie di uscita imperative e non ti richiedono d'imparare complesse tecniche di programmazione funzionale o reattive. ->Examples +>Esempi > ->[Hooks at a Glance](/docs/hooks-overview.html) is a good place to start learning Hooks. +>[Panoramica sugli Hooks](/docs/hooks-overview.html) è un buon punto di partenza per imparare gli Hooks. -## Gradual Adoption Strategy {#gradual-adoption-strategy} +## Strategie di Adozione Graduale {#gradual-adoption-strategy} ->**TLDR: There are no plans to remove classes from React.** +>**TLDR: Non abbiamo piani per rimuovere le classi da React.** -We know that React developers are focused on shipping products and don't have time to look into every new API that's being released. Hooks are very new, and it might be better to wait for more examples and tutorials before considering learning or adopting them. +Sappiamo che gli sviluppatori React sono focalizzati allo sviluppo di prodotti e non hanno tempo per osservare ogni nuova API appena rilasciata. Gli Hooks sono molto nuovi e potrebbe essere meglio aspettare più esempi e tutorials prima di considerarne l'apprendimento o l'adozione. -We also understand that the bar for adding a new primitive to React is extremely high. For curious readers, we have prepared a [detailed RFC](https://github.com/reactjs/rfcs/pull/68) that dives into motivation with more details, and provides extra perspective on the specific design decisions and related prior art. +Sappiamo anche che la barra per aggiungere una nuova primitiva in React è estremamente alta. Per i lettori più curiosi, abbiamo preparato una [RFC dettagliata](https://github.com/reactjs/rfcs/pull/68) che spiega in dettaglio le motivazioni ed offre una prospettiva aggiuntiva riguardo le decisioni di design oltre riferimenti ad opere precedenti correlate. -**Crucially, Hooks work side-by-side with existing code so you can adopt them gradually.** There is no rush to migrate to Hooks. We recommend avoiding any "big rewrites", especially for existing, complex class components. It takes a bit of a mindshift to start "thinking in Hooks". In our experience, it's best to practice using Hooks in new and non-critical components first, and ensure that everybody on your team feels comfortable with them. After you give Hooks a try, please feel free to [send us feedback](https://github.com/facebook/react/issues/new), positive or negative. +**È importante notare che gli Hooks funzionano a fianco al codice esistente, puoi quindi adottarli in modo graduale.** Non c'è fretta nella migrazione agli Hooks. Raccomandiamo di evitare "grandi riscritture", specialmente per componenti classe complessi già esistenti. "Pensare in Hooks" richiede un po' di cambiamenti mentali. Nella nostra esperienza, è meglio far pratica partendo da componenti nuovi e non critici, assicurandosi che tutti i membri del tuo team siano a proprio agio. Dopo che hai avuto l'opportunità di provare gli Hooks, [inviaci pure un feedback](https://github.com/facebook/react/issues/new), positivo o negativo. -We intend for Hooks to cover all existing use cases for classes, but **we will keep supporting class components for the foreseeable future.** At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes. +Vogliamo far sì che gli Hooks coprano tutti i casi d'uso delle classi, tuttavia **continueremo a supportare i componenti classe per il futuro prevedibile.** In Facebook, abbiamo decine di migliaia di componenti scritti come classi, non abbiamo assolutamente alcun piano per riscriverli. Piuttosto, stiamo cominciando ad utilizzare gli Hooks nel nuovo codice a fianco al codice scritto usando le classi. -## Frequently Asked Questions {#frequently-asked-questions} +## Domande Frequenti {#frequently-asked-questions} -We've prepared a [Hooks FAQ page](/docs/hooks-faq.html) that answers the most common questions about Hooks. +Abbiamo preparato una pagina [FAQ sugli Hooks](/docs/hooks-faq.html) che risponde alle domande più frequenti riguardo agli Hooks. -## Next Steps {#next-steps} +## Passi Successivi {#next-steps} -By the end of this page, you should have a rough idea of what problems Hooks are solving, but many details are probably unclear. Don't worry! **Let's now go to [the next page](/docs/hooks-overview.html) where we start learning about Hooks by example.** +Alla fine di questa pagina, dovresti avere un'idea dei problemi che gli Hooks cercano di risolvere, anche se molti dettagli ti sembrano probabilmente non molto chiari. Non preoccuparti! **Andiamo alla [pagina successiva](/docs/hooks-overview.html) dove incominceremo ad imparare gli Hooks con esempi.**