# Топ 30 питань на співбесіді з React: повний посібник для успіху > 30 найчастіших питань на співбесіді з React у 2026 році. Детальні відповіді, приклади коду та поради для отримання роботи React-розробника. - Published: 2026-01-31 - Updated: 2026-04-21 - Author: SharpSkill - Tags: react interview, frontend interview, react questions, javascript, technical interview - Reading time: 18 min --- Технічні співбесіди з React перевіряють розуміння фундаментальних концепцій, просунутих патернів та найкращих практик. Цей посібник містить 30 найчастіших питань із детальними відповідями та прикладами коду для ефективної підготовки. > **Порада щодо підготовки** > > Ці питання впорядковані за рівнем складності. Опанування основ перед переходом до складних концепцій дозволяє побудувати більш послідовну підготовку. ## Основи React ### 1. Що таке Virtual DOM і чому React його використовує? Virtual DOM — це легке JavaScript-представлення реального DOM. React використовує цю абстракцію, щоб оптимізувати оновлення інтерфейсу. Процес складається з трьох кроків: React спочатку створює віртуальну копію DOM, потім порівнює цю копію з попередньою версією під час змін (алгоритм diffing), і нарешті застосовує до реального DOM лише необхідні модифікації (реконсиляція). ```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}
) } ``` Такий підхід уникає витратних операцій над DOM і забезпечує швидкі оновлення навіть у складних інтерфейсах. ### 2. Яка різниця між функціональними та класовими компонентами? Функціональні компоненти — це JavaScript-функції, які приймають props і повертають JSX. Починаючи з React 16.8, хуки дозволяють використовувати стан та життєвий цикл у функціональних компонентах. ```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

Hello {this.props.name}, visit #{this.state.visits}

} } ``` Функціональні компоненти наразі є стандартом. Класові компоненти залишаються підтримуваними, але вже не рекомендуються для нових проєктів. ### 3. Як працює JSX? JSX — це синтаксичне розширення JavaScript, яке дозволяє писати розмітку безпосередньо в коді. Це не HTML, а замаскований JavaScript. ```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') ) ``` Відмінності від HTML: `className` замість `class`, `htmlFor` замість `for`, camelCase для атрибутів (`onClick`, `tabIndex`) та обов'язкове закриття самозакривних тегів. ### 4. Що таке state проти props? Props — це дані, які батьківський компонент передає дочірньому. Вони доступні лише для читання. State — це внутрішній стан компонента, що змінюється через сетери. ```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 ``` Фундаментальне правило: props передаються вниз (батько → дитина), а state є локальним для кожного компонента. ### 5. Чому ключі важливі у списках? Ключі допомагають React визначити, які елементи змінилися, додалися або були видалені у списку. Без унікальних і стабільних ключів React може поводитися непередбачувано. ```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. Поясніть useState та його поширені пастки `useState` керує локальним станом у функціональному компоненті. Сетер може приймати значення або функцію оновлення. ```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. Як працює useEffect зі своїм масивом залежностей? `useEffect` виконує побічні ефекти після рендеру. Масив залежностей контролює, коли ефект спрацьовує. ```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) }, []) ``` > **Правило ESLint** > > Завжди варто вмикати `eslint-plugin-react-hooks` для виявлення відсутніх залежностей. Це правило запобігає багатьом важко діагностованим помилкам. ### 8. Коли використовувати useMemo та useCallback? Ці хуки дозволяють мемоізувати обчислення та функції, щоб уникнути непотрібних повторних обчислень або створень. Їх не варто використовувати надмірно. ```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} } ``` Ці хуки слід застосовувати лише тоді, коли виявлено реальну проблему продуктивності, або для стабілізації посилань, що передаються у мемоізовані компоненти. ### 9. Як працює useRef і які його випадки використання? `useRef` створює змінне посилання, що зберігається між рендерами без запуску повторного рендеру при зміні. ```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. Поясніть useContext і коли його використовувати `useContext` дає доступ до React-контексту без передачі пропсів через усі рівні. Підходить для глобальних даних на кшталт теми або поточного користувача. ```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 (