Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 27 additions & 20 deletions src/content/reference/react/PureComponent.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
---
title: PureComponent
translationStatus: ai-draft
---

<Note>

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/PureComponent.md).

</Note>

<Pitfall>

We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives)
Consigliamo di definire i componenti come funzioni invece che come classi. [Vedi come migrare.](#alternatives)

</Pitfall>

<Intro>

`PureComponent` is similar to [`Component`](/reference/react/Component) but it skips re-renders for same props and state. Class components are still supported by React, but we don't recommend using them in new code.
`PureComponent` è simile a [`Component`](/reference/react/Component) ma salta le ri-renderizzazioni quando props e state sono gli stessi. I componenti classe sono ancora supportati da React, ma non consigliamo di usarli nel codice nuovo.

```js
class Greeting extends PureComponent {
Expand All @@ -30,7 +37,7 @@ class Greeting extends PureComponent {

### `PureComponent` {/*purecomponent*/}

To skip re-rendering a class component for same props and state, extend `PureComponent` instead of [`Component`:](/reference/react/Component)
Per saltare la ri-renderizzazione di un componente classe quando props e state sono gli stessi, estendi `PureComponent` invece di [`Component`:](/reference/react/Component)

```js
import { PureComponent } from 'react';
Expand All @@ -42,18 +49,18 @@ class Greeting extends PureComponent {
}
```

`PureComponent` is a subclass of `Component` and supports [all the `Component` APIs.](/reference/react/Component#reference) Extending `PureComponent` is equivalent to defining a custom [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) method that shallowly compares props and state.
`PureComponent` è una sottoclasse di `Component` e supporta [tutte le API di `Component`.](/reference/react/Component#reference) Estendere `PureComponent` equivale a definire un metodo [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) personalizzato che confronta superficialmente props e state.


[See more examples below.](#usage)
[Vedi altri esempi sotto.](#usage)

---

## Usage {/*usage*/}

### Skipping unnecessary re-renders for class components {/*skipping-unnecessary-re-renders-for-class-components*/}
### Saltare ri-renderizzazioni non necessarie per i componenti classe {/*skipping-unnecessary-re-renders-for-class-components*/}

React normally re-renders a component whenever its parent re-renders. As an optimization, you can create a component that React will not re-render when its parent re-renders so long as its new props and state are the same as the old props and state. [Class components](/reference/react/Component) can opt into this behavior by extending `PureComponent`:
Di norma React ri-renderizza un componente ogni volta che il genitore viene ri-renderizzato. Come ottimizzazione, puoi creare un componente che React non ri-renderizzerà quando il genitore viene ri-renderizzato, purché le nuove props e lo state siano uguali alle vecchie props e allo state precedente. I [componenti classe](/reference/react/Component) possono adottare questo comportamento estendendo `PureComponent`:

```js {1}
class Greeting extends PureComponent {
Expand All @@ -63,9 +70,9 @@ class Greeting extends PureComponent {
}
```

A React component should always have [pure rendering logic.](/learn/keeping-components-pure) This means that it must return the same output if its props, state, and context haven't changed. By using `PureComponent`, you are telling React that your component complies with this requirement, so React doesn't need to re-render as long as its props and state haven't changed. However, your component will still re-render if a context that it's using changes.
Un componente React dovrebbe sempre avere [logica di renderizzazione pura.](/learn/keeping-components-pure) Ciò significa che deve restituire lo stesso output se props, state e context non sono cambiati. Usando `PureComponent`, stai dicendo a React che il tuo componente rispetta questo requisito, quindi React non ha bisogno di ri-renderizzarlo finché props e state non sono cambiati. Tuttavia, il tuo componente verrà comunque ri-renderizzato se cambia un context che sta usando.

In this example, notice that the `Greeting` component re-renders whenever `name` is changed (because that's one of its props), but not when `address` is changed (because it's not passed to `Greeting` as a prop):
In questo esempio, nota che il componente `Greeting` viene ri-renderizzato ogni volta che cambia `name` (perché è una delle sue props), ma non quando cambia `address` (perché non viene passato a `Greeting` come prop):

<Sandpack>

Expand All @@ -85,11 +92,11 @@ export default function MyApp() {
return (
<>
<label>
Name{': '}
Nome{': '}
<input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Address{': '}
Indirizzo{': '}
<input value={address} onChange={e => setAddress(e.target.value)} />
</label>
<Greeting name={name} />
Expand All @@ -109,17 +116,17 @@ label {

<Pitfall>

We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives)
Consigliamo di definire i componenti come funzioni invece che come classi. [Vedi come migrare.](#alternatives)

</Pitfall>

---

## Alternatives {/*alternatives*/}

### Migrating from a `PureComponent` class component to a function {/*migrating-from-a-purecomponent-class-component-to-a-function*/}
### Migrare da un componente classe `PureComponent` a una funzione {/*migrating-from-a-purecomponent-class-component-to-a-function*/}

We recommend using function components instead of [class components](/reference/react/Component) in new code. If you have some existing class components using `PureComponent`, here is how you can convert them. This is the original code:
Nel codice nuovo consigliamo di usare componenti funzione al posto dei [componenti classe](/reference/react/Component). Se hai componenti classe esistenti che usano `PureComponent`, ecco come convertirli. Questo è il codice originale:

<Sandpack>

Expand All @@ -139,11 +146,11 @@ export default function MyApp() {
return (
<>
<label>
Name{': '}
Nome{': '}
<input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Address{': '}
Indirizzo{': '}
<input value={address} onChange={e => setAddress(e.target.value)} />
</label>
<Greeting name={name} />
Expand All @@ -161,7 +168,7 @@ label {

</Sandpack>

When you [convert this component from a class to a function,](/reference/react/Component#alternatives) wrap it in [`memo`:](/reference/react/memo)
Quando [converti questo componente da classe a funzione,](/reference/react/Component#alternatives) avvolgilo in [`memo`:](/reference/react/memo)

<Sandpack>

Expand All @@ -179,11 +186,11 @@ export default function MyApp() {
return (
<>
<label>
Name{': '}
Nome{': '}
<input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Address{': '}
Indirizzo{': '}
<input value={address} onChange={e => setAddress(e.target.value)} />
</label>
<Greeting name={name} />
Expand All @@ -203,6 +210,6 @@ label {

<Note>

Unlike `PureComponent`, [`memo`](/reference/react/memo) does not compare the new and the old state. In function components, calling the [`set` function](/reference/react/useState#setstate) with the same state [already prevents re-renders by default,](/reference/react/memo#updating-a-memoized-component-using-state) even without `memo`.
A differenza di `PureComponent`, [`memo`](/reference/react/memo) non confronta il nuovo e il vecchio state. Nei componenti funzione, chiamare una [funzione `set`](/reference/react/useState#setstate) con lo stesso state [previene già di default la ri-renderizzazione,](/reference/react/memo#updating-a-memoized-component-using-state) anche senza `memo`.

</Note>
75 changes: 41 additions & 34 deletions src/content/reference/react/isValidElement.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
---
title: isValidElement
translationStatus: ai-draft
---

<Note>

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/isValidElement.md).

</Note>

<Intro>

`isValidElement` checks whether a value is a React element.
`isValidElement` ti permette di verificare se un valore è un elemento React.

```js
const isElement = isValidElement(value)
Expand All @@ -20,68 +27,68 @@ const isElement = isValidElement(value)

### `isValidElement(value)` {/*isvalidelement*/}

Call `isValidElement(value)` to check whether `value` is a React element.
Chiama `isValidElement(value)` per verificare se `value` è un elemento React.

```js
import { isValidElement, createElement } from 'react';

// ✅ React elements
// ✅ Elementi React
console.log(isValidElement(<p />)); // true
console.log(isValidElement(createElement('p'))); // true

// ❌ Not React elements
// ❌ Non sono elementi React
console.log(isValidElement(25)); // false
console.log(isValidElement('Hello')); // false
console.log(isValidElement({ age: 42 })); // false
```

[See more examples below.](#usage)
[Vedi altri esempi sotto.](#usage)

#### Parameters {/*parameters*/}

* `value`: The `value` you want to check. It can be any a value of any type.
* `value`: Il valore che vuoi verificare. Può essere di qualsiasi tipo.

#### Returns {/*returns*/}

`isValidElement` returns `true` if the `value` is a React element. Otherwise, it returns `false`.
`isValidElement` restituisce `true` se `value` è un elemento React. Altrimenti, restituisce `false`.

#### Caveats {/*caveats*/}

* **Only [JSX tags](/learn/writing-markup-with-jsx) and objects returned by [`createElement`](/reference/react/createElement) are considered to be React elements.** For example, even though a number like `42` is a valid React *node* (and can be returned from a component), it is not a valid React element. Arrays and portals created with [`createPortal`](/reference/react-dom/createPortal) are also *not* considered to be React elements.
* **Solo i [tag JSX](/learn/writing-markup-with-jsx) e gli oggetti restituiti da [`createElement`](/reference/react/createElement) sono considerati elementi React.** Ad esempio, anche se un numero come `42` è un *nodo React* valido (e può essere restituito da un componente), non è un elemento React valido. Anche gli array e i [portali](/reference/react-dom/createPortal) creati con [`createPortal`](/reference/react-dom/createPortal) *non* sono considerati elementi React.

---

## Usage {/*usage*/}

### Checking if something is a React element {/*checking-if-something-is-a-react-element*/}
### Verificare se qualcosa è un elemento React {/*checking-if-something-is-a-react-element*/}

Call `isValidElement` to check if some value is a *React element.*
Chiama `isValidElement` per verificare se un valore è un *elemento React.*

React elements are:
Gli elementi React sono:

- Values produced by writing a [JSX tag](/learn/writing-markup-with-jsx)
- Values produced by calling [`createElement`](/reference/react/createElement)
- Valori prodotti scrivendo un [tag JSX](/learn/writing-markup-with-jsx)
- Valori prodotti chiamando [`createElement`](/reference/react/createElement)

For React elements, `isValidElement` returns `true`:
Per gli elementi React, `isValidElement` restituisce `true`:

```js
import { isValidElement, createElement } from 'react';

// ✅ JSX tags are React elements
// ✅ I tag JSX sono elementi React
console.log(isValidElement(<p />)); // true
console.log(isValidElement(<MyComponent />)); // true

// ✅ Values returned by createElement are React elements
// ✅ I valori restituiti da createElement sono elementi React
console.log(isValidElement(createElement('p'))); // true
console.log(isValidElement(createElement(MyComponent))); // true
```

Any other values, such as strings, numbers, or arbitrary objects and arrays, are not React elements.
Qualsiasi altro valore, come stringhe, numeri o oggetti e array arbitrari, non è un elemento React.

For them, `isValidElement` returns `false`:
Per questi, `isValidElement` restituisce `false`:

```js
// ❌ These are *not* React elements
// ❌ Questi *non* sono elementi React
console.log(isValidElement(null)); // false
console.log(isValidElement(25)); // false
console.log(isValidElement('Hello')); // false
Expand All @@ -90,39 +97,39 @@ console.log(isValidElement([<div />, <div />])); // false
console.log(isValidElement(MyComponent)); // false
```

It is very uncommon to need `isValidElement`. It's mostly useful if you're calling another API that *only* accepts elements (like [`cloneElement`](/reference/react/cloneElement) does) and you want to avoid an error when your argument is not a React element.
È molto raro aver bisogno di `isValidElement`. È soprattutto utile se stai chiamando un'altra API che accetta *solo* elementi (come fa [`cloneElement`](/reference/react/cloneElement)) e vuoi evitare un errore quando il tuo argomento non è un elemento React.

Unless you have some very specific reason to add an `isValidElement` check, you probably don't need it.
A meno che tu non abbia un motivo molto specifico per aggiungere un controllo con `isValidElement`, probabilmente non ne hai bisogno.

<DeepDive>

#### React elements vs React nodes {/*react-elements-vs-react-nodes*/}
#### Elementi React vs nodi React {/*react-elements-vs-react-nodes*/}

When you write a component, you can return any kind of *React node* from it:
Quando scrivi un componente, puoi restituire qualsiasi tipo di *nodo React*:

```js
function MyComponent() {
// ... you can return any React node ...
// ... puoi restituire qualsiasi nodo React ...
}
```

A React node can be:
Un nodo React può essere:

- A React element created like `<div />` or `createElement('div')`
- A portal created with [`createPortal`](/reference/react-dom/createPortal)
- A string
- A number
- `true`, `false`, `null`, or `undefined` (which are not displayed)
- An array of other React nodes
- Un elemento React creato come `<div />` o `createElement('div')`
- Un [portale](/reference/react-dom/createPortal) creato con [`createPortal`](/reference/react-dom/createPortal)
- Una stringa
- Un numero
- `true`, `false`, `null` o `undefined` (che non vengono visualizzati)
- Un array di altri nodi React

**Note `isValidElement` checks whether the argument is a *React element,* not whether it's a React node.** For example, `42` is not a valid React element. However, it is a perfectly valid React node:
**Nota `isValidElement` verifica se l'argomento è un *elemento React,* non se è un nodo React.** Ad esempio, `42` non è un elemento React valido. Tuttavia, è un nodo React perfettamente valido:

```js
function MyComponent() {
return 42; // It's ok to return a number from component
return 42; // Va bene restituire un numero da un componente
}
```

This is why you shouldn't use `isValidElement` as a way to check whether something can be rendered.
Per questo non dovresti usare `isValidElement` per verificare se qualcosa può essere renderizzato.

</DeepDive>
Loading