# Top 30 Domande da Colloquio React
> Guida completa alle 30 domande più frequenti nei colloqui tecnici React, con risposte dettagliate ed esempi di codice.
- Published: 2026-01-31
- Updated: 2026-04-21
- Author: SharpSkill
- Tags: react interview, frontend interview, react questions, javascript, technical interview
- Reading time: 18 min
---
I colloqui tecnici React valutano la comprensione dei concetti fondamentali, dei pattern avanzati e delle best practice. Questa guida raccoglie le 30 domande più frequenti, con risposte dettagliate ed esempi di codice per prepararsi al colloquio in modo efficace.
> **Consiglio di preparazione**
>
> Queste domande sono organizzate per livello di difficoltà. Padroneggiare i fondamenti prima di affrontare i concetti avanzati permette di costruire una preparazione più solida.
## Fondamenti di React
### 1. Che cos'è il Virtual DOM e perché React lo utilizza?
Il Virtual DOM è una rappresentazione leggera in JavaScript del DOM reale. React utilizza questa astrazione per ottimizzare gli aggiornamenti dell'interfaccia.
Il processo si svolge in tre fasi: React crea prima una copia virtuale del DOM, poi confronta questa copia con la versione precedente quando si verificano cambiamenti (algoritmo di diffing) e infine applica al DOM reale solo le modifiche necessarie (reconciliation).
```jsx
// Simplified example of the concept
// When state changes, React doesn't recreate the entire DOM
function Counter() {
const [count, setCount] = useState(0)
// Only the span containing count will be updated in the real DOM
// The rest of the component is untouched
return (
Counter
{count}
)
}
```
Questo approccio evita operazioni costose sul DOM e consente aggiornamenti performanti anche in interfacce complesse.
### 2. Qual è la differenza tra componenti funzionali e componenti classe?
I componenti funzionali sono funzioni JavaScript che ricevono props e restituiscono JSX. Da React 16.8 gli hook permettono di usare stato e ciclo di vita all'interno dei componenti funzionali.
```jsx
// Functional component (recommended)
// More concise, easier to test, supports hooks
function Welcome({ name }) {
const [visits, setVisits] = useState(0)
useEffect(() => {
setVisits(v => v + 1)
}, [])
return
Hello {name}, visit #{visits}
}
// Class component (legacy)
// More verbose, requires this binding
class WelcomeClass extends React.Component {
state = { visits: 0 }
componentDidMount() {
this.setState(prev => ({ visits: prev.visits + 1 }))
}
render() {
return
}
}
```
I componenti funzionali sono oggi lo standard. I componenti classe restano supportati ma non sono più consigliati per i nuovi progetti.
### 3. Come funziona JSX?
JSX è un'estensione di sintassi per JavaScript che permette di scrivere markup all'interno del codice. Non è HTML, ma JavaScript sotto mentite spoglie.
```jsx
// What we write (JSX)
const element = (
Title
Paragraph
)
// What Babel compiles (pure JavaScript)
const element = React.createElement(
'div',
{ className: 'container' },
React.createElement('h1', null, 'Title'),
React.createElement('p', null, 'Paragraph')
)
```
Tra le differenze rispetto all'HTML: `className` al posto di `class`, `htmlFor` al posto di `for`, camelCase per gli attributi (`onClick`, `tabIndex`) e chiusura obbligatoria dei tag auto-chiudenti.
### 4. Qual è la differenza tra state e props?
Le props sono dati passati da un componente padre a un figlio. Sono in sola lettura. Lo state è lo stato interno di un componente, modificabile tramite setter.
```jsx
// UserCard.jsx
// name and role are props (immutable)
function UserCard({ name, role }) {
// isExpanded is state (mutable)
const [isExpanded, setIsExpanded] = useState(false)
return (
{name}
{role}
{/* Modifying state triggers a re-render */}
{isExpanded && }
)
}
// Usage
```
La regola fondamentale: le props scendono dall'alto (padre → figlio), lo state è locale a ciascun componente.
### 5. Perché le key sono importanti nelle liste?
Le key aiutano React a identificare quali elementi sono stati modificati, aggiunti o rimossi in una lista. Senza key uniche e stabili React può presentare comportamenti inattesi.
```jsx
// ❌ Bad practice: index as key
// Problem: if order changes, React loses tracking
{items.map((item, index) => (
))}
// ✅ Good practice: unique and stable identifier
{items.map(item => (
))}
// Concrete example of the problem with indices
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Create a project' }
])
// When deleting the first element with key={index}
// React will think element 0's content changed
// instead of understanding an element was removed
return (
{todos.map(todo => (
{todo.text}
))}
)
}
```
## React Hooks
### 6. Spiegare useState e le sue insidie comuni
`useState` gestisce lo stato locale in un componente funzionale. Il setter può ricevere un valore oppure una funzione di aggiornamento.
```jsx
// Declaration with initial value
const [count, setCount] = useState(0)
// ❌ Pitfall: multiple updates in the same cycle
function increment() {
setCount(count + 1) // count = 0, sets 1
setCount(count + 1) // count = 0 still, sets 1
setCount(count + 1) // count = 0 still, sets 1
// Final result: 1 (not 3)
}
// ✅ Solution: use the update function
function incrementCorrect() {
setCount(prev => prev + 1) // 0 → 1
setCount(prev => prev + 1) // 1 → 2
setCount(prev => prev + 1) // 2 → 3
// Final result: 3
}
// ❌ Pitfall: object mutation
const [user, setUser] = useState({ name: 'Alice', age: 25 })
user.age = 26 // Direct mutation, no re-render
// ✅ Solution: create a new object
setUser({ ...user, age: 26 })
// or
setUser(prev => ({ ...prev, age: 26 }))
```
### 7. Come funziona useEffect con l'array delle dipendenze?
`useEffect` esegue effetti collaterali dopo il render. L'array delle dipendenze controlla quando l'effetto viene eseguito.
```jsx
// Executed on every render (rare, usually avoid)
useEffect(() => {
console.log('Render completed')
})
// Executed only on mount (equivalent to componentDidMount)
useEffect(() => {
console.log('Component mounted')
// Cleanup on unmount (equivalent to componentWillUnmount)
return () => {
console.log('Component unmounted')
}
}, [])
// Executed when userId changes
useEffect(() => {
async function fetchUser() {
const response = await fetch(`/api/users/${userId}`)
const data = await response.json()
setUser(data)
}
fetchUser()
}, [userId])
// ❌ Missing dependency - subtle bug
useEffect(() => {
const timer = setInterval(() => {
setCount(count + 1) // count is "captured" at its initial value
}, 1000)
return () => clearInterval(timer)
}, []) // count is missing from dependencies
// ✅ Fix with update function
useEffect(() => {
const timer = setInterval(() => {
setCount(prev => prev + 1) // No need for count in deps
}, 1000)
return () => clearInterval(timer)
}, [])
```
> **Regola ESLint**
>
> Abilitare sempre `eslint-plugin-react-hooks` per rilevare le dipendenze mancanti. Questa regola previene molti bug difficili da diagnosticare.
### 8. Quando usare useMemo e useCallback?
Questi hook permettono la memoizzazione per evitare ricalcoli o ricreazioni inutili. Occorre però non abusarne.
```jsx
// useMemo: memoizes a computed value
function ProductList({ products, filter }) {
// Recalculated only if products or filter change
const filteredProducts = useMemo(() => {
console.log('Filtering...')
return products.filter(p => p.category === filter)
}, [products, filter])
return
{filteredProducts.map(p =>
{p.name}
)}
}
// useCallback: memoizes a function
function ParentComponent() {
const [count, setCount] = useState(0)
// Without useCallback, handleClick is recreated on every render
// Causing unnecessary re-renders of ExpensiveChild
const handleClick = useCallback((id) => {
console.log('Clicked:', id)
}, []) // Empty deps = stable function
return (
<>
{count}
{/* React.memo on ExpensiveChild for this to be effective */}
>
)
}
// ❌ Over-optimization: not needed here
const SimpleComponent = () => {
// This calculation is trivial, useMemo adds overhead
const doubled = useMemo(() => 2 * 2, [])
return {doubled}
}
```
Questi hook vanno utilizzati solo quando è stato individuato un problema di performance o per stabilizzare riferimenti passati a componenti memoizzati.
### 9. Come funziona useRef e quali sono i suoi casi d'uso?
`useRef` crea un riferimento mutabile che persiste tra i render senza innescare un re-render quando cambia.
```jsx
// Case 1: Access a DOM element
function TextInput() {
const inputRef = useRef(null)
const focusInput = () => {
inputRef.current.focus()
}
return (
<>
>
)
}
// Case 2: Store a mutable value without re-render
function Timer() {
const [seconds, setSeconds] = useState(0)
const intervalRef = useRef(null)
const start = () => {
// Store the interval ID to be able to stop it
intervalRef.current = setInterval(() => {
setSeconds(s => s + 1)
}, 1000)
}
const stop = () => {
clearInterval(intervalRef.current)
}
return (
{seconds}s
)
}
// Case 3: Keep the previous value
function usePrevious(value) {
const ref = useRef()
useEffect(() => {
ref.current = value
}, [value])
return ref.current
}
```
### 10. Spiegare useContext e quando utilizzarlo
`useContext` accede a un context React senza prop drilling. Ideale per dati globali come tema o utente autenticato.
```jsx
// 1. Create the context
const ThemeContext = createContext({
theme: 'light',
toggleTheme: () => {}
})
// 2. Create the provider
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light')
const toggleTheme = useCallback(() => {
setTheme(prev => prev === 'light' ? 'dark' : 'light')
}, [])
// Memoize the value to avoid unnecessary re-renders
const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme])
return (
{children}
)
}
// 3. Use the context
function ThemedButton() {
const { theme, toggleTheme } = useContext(ThemeContext)
return (
)
}
// 4. Wrap the application
function App() {
return (
)
}
```
## Pattern avanzati
### 11. Che cos'è un Higher-Order Component (HOC)?
Un HOC è una funzione che riceve un componente e restituisce un nuovo componente arricchito. Meno diffuso dall'arrivo degli hook, ma ancora presente in alcune librerie.
```jsx
// HOC that adds logging
function withLogging(WrappedComponent) {
return function WithLogging(props) {
useEffect(() => {
console.log(`${WrappedComponent.name} mounted with props:`, props)
return () => {
console.log(`${WrappedComponent.name} unmounted`)
}
}, [])
return
}
}
// HOC that handles authentication
function withAuth(WrappedComponent) {
return function WithAuth(props) {
const { user, isLoading } = useAuth()
if (isLoading) return
if (!user) return
return
}
}
// Usage
const ProtectedDashboard = withAuth(Dashboard)
const LoggedButton = withLogging(Button)
```
### 12. Spiegare il pattern Render Props
Il pattern Render Props condivide logica tra componenti tramite una prop che è una funzione.
```jsx
// Component with render prop
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 })
useEffect(() => {
const handleMove = (e) => {
setPosition({ x: e.clientX, y: e.clientY })
}
window.addEventListener('mousemove', handleMove)
return () => window.removeEventListener('mousemove', handleMove)
}, [])
// Call the render function with data
return render(position)
}
// Usage
function App() {
return (
(
Position: {x}, {y}
)}
/>
)
}
// Modern version with custom hook (preferred)
function useMousePosition() {
const [position, setPosition] = useState({ x: 0, y: 0 })
useEffect(() => {
const handleMove = (e) => {
setPosition({ x: e.clientX, y: e.clientY })
}
window.addEventListener('mousemove', handleMove)
return () => window.removeEventListener('mousemove', handleMove)
}, [])
return position
}
function App() {
const { x, y } = useMousePosition()
return
Position: {x}, {y}
}
```
### 13. Come creare un custom hook?
I custom hook estraggono e riutilizzano logica con stato tra i componenti.
```jsx
// useLocalStorage.js
function useLocalStorage(key, initialValue) {
// Initialize with localStorage value or default
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
console.error(error)
return initialValue
}
})
// Setter wrapper that syncs with localStorage
const setValue = useCallback((value) => {
try {
// Support update functions
const valueToStore = value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)
window.localStorage.setItem(key, JSON.stringify(valueToStore))
} catch (error) {
console.error(error)
}
}, [key, storedValue])
return [storedValue, setValue]
}
// Usage
function Settings() {
const [theme, setTheme] = useLocalStorage('theme', 'light')
const [fontSize, setFontSize] = useLocalStorage('fontSize', 16)
return (
setFontSize(Number(e.target.value))}
/>
)
}
```
### 14. Che cos'è il pattern Compound Components?
Questo pattern crea componenti che collaborano in modo implicito, come i tag `