# Top 30 pytań rekrutacyjnych z Reacta (2026)
> 30 najważniejszych pytań rekrutacyjnych z Reacta wraz ze szczegółowymi odpowiedziami, przykładami kodu i nowoczesnymi wzorcami.
- Published: 2026-01-31
- Updated: 2026-04-21
- Author: SharpSkill
- Tags: react interview, frontend interview, react questions, javascript, technical interview
- Reading time: 18 min
---
Techniczne rozmowy rekrutacyjne z Reacta sprawdzają znajomość fundamentalnych pojęć, zaawansowanych wzorców oraz dobrych praktyk. Niniejszy przewodnik prezentuje 30 pytań pojawiających się najczęściej, wraz ze szczegółowymi odpowiedziami i przykładami kodu, aby przygotowanie było skuteczne.
> **Rada dotycząca przygotowania**
>
> Pytania zostały ułożone według stopnia trudności. Opanowanie podstaw przed przejściem do zaawansowanych zagadnień pozwala zbudować bardziej uporządkowane przygotowanie.
## Fundamenty Reacta
### 1. Czym jest Virtual DOM i dlaczego React go stosuje?
Virtual DOM to lekka reprezentacja prawdziwego DOM w JavaScript. React używa tej abstrakcji do optymalizowania aktualizacji interfejsu.
Proces przebiega w trzech krokach: React najpierw tworzy wirtualną kopię DOM, następnie porównuje ją z poprzednią wersją po wystąpieniu zmian (algorytm diffingu), a na końcu stosuje w prawdziwym DOM wyłącznie niezbędne modyfikacje (rekoncyliacja).
```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}
)
}
```
Takie podejście pozwala uniknąć kosztownych operacji na DOM i umożliwia wydajne aktualizacje nawet w złożonych interfejsach.
### 2. Jaka jest różnica między komponentami funkcyjnymi a klasowymi?
Komponenty funkcyjne to funkcje JavaScript, które przyjmują propsy i zwracają JSX. Od wersji React 16.8 hooki umożliwiają korzystanie ze stanu i cyklu życia w komponentach funkcyjnych.
```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
}
}
```
Komponenty funkcyjne stanowią obecnie standard. Komponenty klasowe są nadal wspierane, jednak nie są już zalecane w nowych projektach.
### 3. Jak działa JSX?
JSX to rozszerzenie składni JavaScriptu pozwalające na zapisywanie znaczników bezpośrednio w kodzie. Nie jest to HTML, lecz JavaScript w przebraniu.
```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')
)
```
Do różnic względem HTML należą: `className` zamiast `class`, `htmlFor` zamiast `for`, camelCase w atrybutach (`onClick`, `tabIndex`) oraz konieczność zamykania tagów samozamykających.
### 4. Czym są state i props?
Propsy to dane przekazywane z komponentu nadrzędnego do potomnego. Są tylko do odczytu. Stan to wewnętrzny stan komponentu, modyfikowany za pomocą setterów.
```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
```
Podstawowa zasada: propsy płyną w dół (rodzic → dziecko), stan pozostaje lokalny dla każdego komponentu.
### 5. Dlaczego klucze są ważne na listach?
Klucze pomagają Reactowi określić, które elementy listy zostały zmienione, dodane lub usunięte. Bez unikalnych i stabilnych kluczy React może zachowywać się w nieoczekiwany sposób.
```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}
))}
)
}
```
## Hooki Reacta
### 6. Jak działa useState i jakie są jego typowe pułapki?
`useState` zarządza lokalnym stanem w komponencie funkcyjnym. Setter przyjmuje wartość lub funkcję aktualizującą.
```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. Jak działa useEffect i jego tablica zależności?
`useEffect` wykonuje efekty uboczne po renderowaniu. Tablica zależności decyduje, kiedy efekt ma się uruchomić.
```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)
}, [])
```
> **Reguła ESLint**
>
> Warto zawsze włączać `eslint-plugin-react-hooks`, aby wykrywać brakujące zależności. Ta reguła pozwala uniknąć wielu trudnych w diagnozie błędów.
### 8. Kiedy stosować useMemo i useCallback?
Te hooki umożliwiają memoizację, aby unikać zbędnych obliczeń i ponownego tworzenia funkcji. Należy jednak uważać na ich nadmierne stosowanie.
```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}
}
```
Hooki te powinny być używane wyłącznie wtedy, gdy zidentyfikowano faktyczny problem wydajnościowy lub gdy potrzebna jest stabilna referencja przekazywana do memoizowanych komponentów.
### 9. Jak działa useRef i jakie są jego zastosowania?
`useRef` tworzy mutowalną referencję, która przetrwa między renderami i nie wywołuje ponownego renderowania po zmianie.
```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. Jak działa useContext i kiedy go używać?
`useContext` zapewnia dostęp do kontekstu Reacta bez potrzeby stosowania prop drillingu. Świetnie nadaje się do danych globalnych, takich jak motyw czy zalogowany użytkownik.
```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 (
)
}
```
## Zaawansowane wzorce
### 11. Czym jest Higher-Order Component (HOC)?
HOC to funkcja, która przyjmuje komponent i zwraca nowy, wzbogacony komponent. Rzadziej stosowany od czasu pojawienia się hooków, ale nadal obecny w niektórych bibliotekach.
```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. Na czym polega wzorzec Render Props?
Wzorzec Render Props współdzieli logikę między komponentami za pomocą propsa będącego funkcją.
```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. Jak stworzyć własny hook?
Własne hooki pozwalają wyodrębnić logikę stanu i ponownie ją wykorzystywać między komponentami.
```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. Czym jest wzorzec Compound Components?
Ten wzorzec tworzy komponenty, które współpracują niejawnie, podobnie jak tagi `