React Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. What is React?

    Correct answer: A library for building user interfaces out of components

    React is responsible only for the UI: it describes the interface as a function of state and updates the DOM efficiently. Routing, data loading and the rest come from libraries (React Router, TanStack Query) or frameworks built on React (Next.js). JSX is a JavaScript syntax extension, not a separate language.

  2. 2. What is the virtual DOM in React?

    Correct answer: A JS description of the UI that React diffs to update the page

    When rendering, components return a tree of React elements - plain JS objects. React compares the new tree with the previous one (reconciliation) and applies minimal changes to the real DOM. It isn't a browser API or a copy of the browser.

  3. 3. What does JSX turn into at build time?

    Correct answer: Function calls that create React elements (jsx())

    <h1 className="t">Hi</h1> is compiled (by Babel, SWC, TypeScript) into a call like jsx("h1", { className: "t", children: "Hi" }), which returns a description object. Browsers don't understand JSX, and React doesn't use innerHTML - that's why strings in JSX are escaped automatically.

  4. 4. How do you set a CSS class on an element in JSX?

    Correct answer: <div className="box">

    JSX is closer to JavaScript, and class is a reserved word, so attributes are named like DOM properties: className, htmlFor instead of for, tabIndex, onClick. data-* and aria-* attributes are written as in HTML.

  5. 5. Why can't you write {if (isAdmin) { <Admin /> }} inside JSX?

    Correct answer: Only expressions are allowed in curly braces, and if is a statement

    Inside {} you can put any JS expression that produces a value: a variable, a function call, a ternary cond ? a : b, cond && a. Statements (if, for) are used outside JSX - before return or in a separate function. React has no <If> component.

  6. 6. Why doesn't the component function card() { ... } work as <card />?

    Correct answer: JSX treats lowercase names as HTML tags

    JSX distinguishes tags by case: <card /> becomes a DOM element card, while <Card /> becomes a call to your component. The declaration form (function or arrow) and the export style don't matter.

  7. 7. How do you return two sibling elements from a component without an extra DOM wrapper?

    Correct answer: Wrap them in a fragment: <>...</> or <Fragment>

    A component must return a single root. A fragment groups elements without adding a DOM node. If the fragment needs a key (e.g. in a list), use the full form <Fragment key={id}>. An array is also allowed, but each element needs a key, otherwise you get a warning.

  8. 8. Can you modify props inside a child component?

    Correct answer: No: props are read-only; the data's owner should change it

    Props are the component's inputs, and it must not mutate them. For a child to change data, the parent passes it a callback (onChange) and keeps the state itself. Mutating an object from props won't trigger a re-render and creates hard-to-find bugs.

  9. 9. How can a child component pass data to its parent?

    Correct answer: The parent passes a callback via props, and the child calls it with the data

    In React, data flows down and events flow up through functions: <Search onChange={setQuery} />, and the child calls props.onChange(value). Mutating props won't re-render the parent, and function components have no access to the parent instance.

  10. 10. What is children in React?

    Correct answer: A prop with the content passed between the component's tags

    <Card><h2>Title</h2></Card> passes the <h2> in props.children. It's the basis of composition: wrappers, layouts and modals accept arbitrary content. children can be a string, an element, an array or a function (the render props pattern).

  11. 11. What does useState(0) return?

    Correct answer: An array of the current value and a function to update it

    const [count, setCount] = useState(0) - array destructuring lets you name the variables however you like. The initial value is used only on the first render. If computing it is expensive, pass a function: useState(() => compute()).

  12. 12. What does console.log print after a click?

    const [count, setCount] = useState(0);
    
    function handleClick() {
      setCount(count + 1);
      console.log(count);
    }

    Correct answer: 0

    State within a render is a "snapshot". setCount schedules a new render, but the count variable in the current function stays the same. The new value is available on the next render. If you need the value right away, compute it into a variable: const next = count + 1.

  13. 13. What will count be after one click if the initial value is 0?

    function handleClick() {
      setCount(count + 1);
      setCount(count + 1);
      setCount(count + 1);
    }

    Correct answer: 1

    All three calls see the same snapshot count = 0 and queue the value 1 three times. To make updates add up, use the functional form: setCount(c => c + 1) - each call gets the previous result, and the total is 3.

  14. 14. Why didn't the component re-render?

    const [user, setUser] = useState({ name: "Ann" });
    
    function rename() {
      user.name = "Bob";
      setUser(user);
    }

    Correct answer: The object was mutated, so the reference is the same

    React compares the new value with the old one via Object.is. It's the same object, so the update is skipped. You need to create a new object: setUser({ ...user, name: "Bob" }). Mutation also breaks optimizations like memo.

  15. 15. What's the right way to add an item to an array in state?

    Correct answer: setItems([...items, item]);

    State must be updated immutably - by creating a new array. push mutates the existing array, and the reference doesn't change. Non-mutating methods: spread, concat, filter, map, slice, toSorted(). Removal: items.filter(i => i.id !== id).

  16. 16. Which value is best for key in a list?

    Correct answer: A stable unique identifier from the data, such as id

    key helps React match elements between renders. An index breaks on insertion, removal and sorting: input state and DOM "move" to other items. A random key changes every render - React recreates all elements and loses their state.

  17. 17. What is rendered if items = []?

    <div>{items.length && <List items={items} />}</div>

    Correct answer: The digit 0 is rendered

    0 && x returns 0, and React renders numbers as text (unlike false, null, undefined). Write an explicit boolean condition: items.length > 0 && ... or a ternary items.length ? <List /> : null.

  18. 18. What's wrong with <button onClick={handleClick()}>?

    Correct answer: The function is called immediately during render, not on click

    onClick needs a function, not the result of calling it. Correct: onClick={handleClick}, or onClick={() => handleClick(id)} if you need arguments. If handleClick changes state, calling it during render causes an infinite loop.

  19. 19. How do you cancel the default form submission behavior in React?

    Correct answer: Call e.preventDefault() in the onSubmit handler

    In React, handlers receive a synthetic event with the same API as the native one. return false, as in old inline HTML handlers, doesn't work here. You can stop bubbling with e.stopPropagation().

  20. 20. What is a controlled input?

    Correct answer: A field whose value is stored in state: value + onChange

    In a controlled field, state is the source of truth: value={text} and onChange={e => setText(e.target.value)}. This makes it easy to validate and format input on the fly. An uncontrolled field keeps its value in the DOM (defaultValue, read via ref or FormData).

  21. 21. React warns: "You provided a value prop to a form field without an onChange handler". What happened?

    Correct answer: The field became read-only: value is set but onChange isn't

    If you set value without onChange, React resets the field to that value on every render, and the user can't type. Fixes: add onChange, use defaultValue for an uncontrolled field, or set readOnly explicitly.

  22. 22. Two sibling components need the same data, which they can change. What should you do first?

    Correct answer: Lift the state to the common parent and pass the value and callbacks via props

    Lifting state up is a basic technique: data should have a single source of truth in the closest common ancestor. Duplicating state and syncing it with effects leads to desync and extra renders. Global stores are needed when state is really used in many places in the tree.

  23. 23. What is prop drilling?

    Correct answer: Passing props through intermediate components that don't need them

    When data from the root is needed deep down, you have to pass it through every level. It's inconvenient but not always a problem. Solutions: composition (pass ready elements via children), Context, global stores.

  24. 24. When does the effect useEffect(() => { ... }, []) run?

    Correct answer: After mounting (twice in dev with StrictMode)

    An empty dependency array means "synchronize after mounting". Effects always run after painting, not before. In development, StrictMode mounts, unmounts and mounts the component again to verify that the effect's cleanup is written correctly.

  25. 25. When does an effect without a dependency array run: useEffect(() => { ... })?

    Correct answer: After every render of the component

    Without the second argument, the effect runs after every render. With [] - only after mounting. With [a, b] - after mounting and whenever a or b changes (compared via Object.is).

  26. 26. When is the function returned from useEffect called?

    Correct answer: Before the effect re-runs and when the component unmounts

    The cleanup function undoes what the effect set up: it unsubscribes from events, clears timers, cancels requests. React calls it before the next run of the effect with new dependencies and when the component is removed.

  27. 27. How does useRef differ from useState?

    Correct answer: Changing ref.current doesn't trigger a re-render

    useRef keeps a mutable value between renders without causing a re-render. It's used for DOM references (<input ref={inputRef}>), timer ids and previous values. If a value affects what's on screen, it belongs in state.

  28. 28. Which rule of hooks is broken?

    function Profile({ id }) {
      if (!id) return null;
      const [data, setData] = useState(null);
      // ...
    }

    Correct answer: The hook is called after a conditional return - the hook order changes

    React matches state to hooks by their call order. If a hook isn't called during some render (because of an early return, a condition or a loop), the order breaks. Call hooks at the top level, before any conditional exits.

  29. 29. Why must a custom hook's name start with use?

    Correct answer: That's how the linter and React know it contains hooks

    The use prefix is a convention that eslint-plugin-react-hooks and the React Compiler rely on. By itself it doesn't memoize anything. A function with no hooks inside shouldn't be named use... - it's a regular utility.

  30. 30. When does a child component re-render by default?

    Correct answer: When the parent re-renders, even with the same props

    A parent render re-renders the whole subtree by default. Other causes: a change in its own state and a change in a context it reads. React.memo (or the React Compiler automatically) lets you skip rendering when props are equal. A re-render isn't a DOM change: the DOM changes only if there's a difference.

  31. 31. How do you set an inline style in JSX?

    Correct answer: style={{ color: "red", fontSize: 14 }}

    style takes an object with camelCase properties. The outer braces embed an expression, the inner ones are an object literal. For most properties, numeric values are interpreted as pixels (fontSize: 14 → 14px).

  32. 32. What steps are needed to pass data via Context?

    Correct answer: createContext → a provider with value → useContext in a descendant

    const ThemeContext = createContext('light') → <ThemeContext value={theme}> (in React 19 you can omit .Provider) → useContext(ThemeContext) in any descendant. When value changes, all components reading this context re-render.

  33. 33. What does useContext(MyContext) return if there's no provider above the component?

    Correct answer: The default value from createContext(defaultValue)

    The default value is used when there's no provider higher in the tree. It's often set to null, with a wrapper hook that throws a clear error: "useAuth must be used within AuthProvider".

  34. 34. Why does <StrictMode> call render and effects twice in development?

    Correct answer: To reveal impure renders and effects without cleanup

    The double call helps find side effects during render (mutations, requests) and missing cleanup in effects. It doesn't happen in the production build. If the double call breaks something, the code has a bug that will show up later anyway.

  35. 35. What is React.lazy used for?

    Correct answer: For lazy-loading a component's code as a separate chunk

    const Admin = lazy(() => import('./Admin')) moves the component into a separate JS chunk loaded on first render. This shrinks the initial bundle. Showing content as you scroll is a different task (Intersection Observer).

  36. 36. What does React.lazy need in order to work?

    Correct answer: Wrap it (or an ancestor) in <Suspense fallback>

    While the code loads, the component "suspends" and the nearest <Suspense> shows its fallback. Declare lazy at module level, not inside a component - otherwise every render creates a new component and loses state. The module must have a default export.

  37. 37. Why does lazy(() => import('./Chart')) fail if Chart.tsx has only export function Chart?

    Correct answer: lazy expects a module with a default export

    The promise from import() must resolve to an object with a default field. For a named export, map it: lazy(() => import('./Chart').then(m => ({ default: m.Chart }))). TypeScript and function components are fully supported.

  38. 38. What's dangerous about dangerouslySetInnerHTML?

    Correct answer: It inserts HTML without escaping - an XSS risk

    React normally escapes strings, so {userInput} is safe. dangerouslySetInnerHTML={{ __html }} inserts markup as is, and <img onerror=...> from user data runs a script. If you really need HTML (e.g. from a CMS), clean it with a sanitizer (DOMPurify).

  39. 39. How do you attach an app to a DOM element in React 18+?

    Correct answer: createRoot(el).render(<App />)

    createRoot from react-dom/client enables React 18+ concurrent features. ReactDOM.render is deprecated and removed in React 19. To hydrate server-rendered HTML, use hydrateRoot. Frameworks like Next.js do this automatically.

  40. 40. What is a "pure" component in React terms?

    Correct answer: No side effects in render, and the same JSX for the same input

    Rendering must be a pure computation: no mutating external variables, no requests, no DOM changes. Side effects belong in event handlers or useEffect. StrictMode, concurrent rendering and the React Compiler rely on purity.

  41. 41. How do you render a list of users from the users array?

    Correct answer: {users.map(u => <li key={u.id}>{u.name}</li>)}

    map returns a new array of elements that React renders. forEach returns undefined, so nothing appears. for is a statement and can't be written inside {}. And don't forget key.

  42. 42. What is Redux?

    Correct answer: A global state store: store, actions, reducers

    In Redux, state lives in a single store, changes only by dispatching actions, and new state is computed by pure reducer functions. This gives predictability, convenient debugging (Redux DevTools, time travel) and middleware. Redux is a separate library, connected to React via react-redux.

  43. 43. What's required of a reducer in classic Redux (without Immer)?

    Correct answer: To be pure and return new state without mutations

    (state, action) => newState with no side effects: no requests, random numbers or mutations. Async logic goes into thunks or RTK Query. In Redux Toolkit you can write "mutating" code - Immer turns it into immutable updates under the hood.

  44. 44. What does configureStore from Redux Toolkit do?

    Correct answer: Creates a store with sensible defaults: thunk, DevTools

    configureStore({ reducer: { todos: todosReducer } }) combines reducers, adds the redux-thunk middleware, hooks up Redux DevTools and, in development, checks for accidental mutations and non-serializable values. Connecting to React is still done via <Provider store={store}>.

  45. 45. What are useSelector and useDispatch for?

    Correct answer: useSelector reads data from the store, useDispatch gives you dispatch

    const todos = useSelector(state => state.todos) re-renders the component only if the selector result changed (by reference). const dispatch = useDispatch(); dispatch(added(todo)). TypeScript projects create typed versions useAppSelector and useAppDispatch.

  46. 46. What does createSlice generate?

    Correct answer: A reducer and action creators for each case reducer

    createSlice({ name: 'todos', initialState, reducers: { added(state, action) {...} } }) returns todosSlice.reducer and todosSlice.actions.added with the type 'todos/added'. This removes classic Redux boilerplate with type constants and switch.

  47. 47. What problem does TanStack Query primarily solve?

    Correct answer: Server state: fetching, caching, background data updates

    Server data lives on the backend and can become stale. TanStack Query handles caching, retries, deduplication, refetching on window focus, pagination and mutations. Client UI state stays in useState, Context or Zustand/Redux.

  48. 48. What must you pass to useQuery?

    Correct answer: queryKey and queryFn

    useQuery({ queryKey: ['todos', id], queryFn: () => fetchTodo(id) }). The key identifies data in the cache: everything the request depends on must be in the key - then the request reruns when id changes. queryFn is any function returning a promise; the library isn't tied to fetch.

  49. 49. How do isPending and isFetching differ in TanStack Query v5?

    Correct answer: isPending - no data yet, isFetching - any request is in flight

    isPending (status pending) means there's no data in the cache yet - show a skeleton. isFetching is true for every request, including background refetches of existing data - a small indicator fits here. In v4, isLoading was used instead of isPending.

  50. 50. What must you do before using useQuery in an app?

    Correct answer: Create a QueryClient and wrap the app in its provider

    QueryClient holds the cache and default settings, and the provider makes it available to hooks. Create the client once (outside a component or via useState), otherwise the cache resets on every render. TanStack Query doesn't need Redux.

  51. 51. How do you give a prop a default value in a function component?

    function Avatar({ size = 40, alt = "" }) {
      return <img width={size} height={size} alt={alt} />;
    }

    Correct answer: With default values in props destructuring

    Destructuring defaults apply when the prop is undefined. defaultProps for function components was deprecated and removed in React 19.

  52. 52. How do you render one of two elements depending on a condition?

    Correct answer: With a ternary: {isLoggedIn ? <Profile /> : <LoginButton />}

    JSX accepts expressions, so ? : works inline. For several branches, compute the element in a variable or a helper function before return.

  53. 53. What should a component return to render nothing?

    Correct answer: null

    Returning null renders nothing but the component still exists (its hooks and state live on). Since React 18, returning undefined is also allowed but null is clearer.

  54. 54. Which attribute links a <label> to an input in JSX?

    Correct answer: htmlFor

    Like className, htmlFor avoids a reserved JavaScript word. Wrapping the input inside <label> also links them without an id.

  55. 55. Why does <img src={url}> without a closing slash fail in JSX?

    Correct answer: JSX requires every tag to be closed, as in <img />

    JSX is stricter than HTML: <br />, <input /> and any component without children need the closing slash.

  56. 56. How do you write a comment inside JSX markup?

    Correct answer: {/* comment */}

    Inside JSX you are in markup mode, so the comment has to be a JavaScript expression in braces. HTML comments are rendered as text or cause errors.

  57. 57. When does onChange fire on a text input in React?

    Correct answer: On every keystroke, like the DOM input event

    React normalizes onChange to fire on each change, unlike the native change event that waits for blur. That makes controlled inputs possible.

  58. 58. How do you pass an argument to a click handler?

    {todos.map((t) => <button key={t.id} onClick={() => remove(t.id)}>×</button>)}

    Correct answer: Use an arrow function: onClick={() => remove(t.id)}

    onClick expects a function. remove(t.id) would run during render and pass its return value as the handler.

  59. 59. How do you stop a click inside a card from also triggering the card's onClick?

    <div onClick={openCard}>
      <button onClick={(e) => { e.stopPropagation(); like(); }}>Like</button>
    </div>

    Correct answer: Call e.stopPropagation() in the inner handler

    React events bubble like DOM events (except onScroll). Returning false doesn't stop anything in React; use stopPropagation or preventDefault explicitly.

  60. 60. Must key values be unique across the whole app?

    Correct answer: No - only among siblings in the same list

    Two different lists can reuse the same ids as keys. key isn't passed to the component as a prop; pass the id separately if the child needs it.

  61. 61. How do you add a key when each list item renders several elements without a wrapper?

    {items.map((item) => (
      <Fragment key={item.id}>
        <dt>{item.term}</dt>
        <dd>{item.text}</dd>
      </Fragment>
    ))}

    Correct answer: Use <Fragment key={...}>, as <> can't take a key

    <></> is shorthand for <Fragment> without attributes. Import Fragment from react when you need a key.

  62. 62. How do you focus an input when a button is clicked?

    const inputRef = useRef(null);
    // <input ref={inputRef} />
    // <button onClick={() => inputRef.current.focus()}>Edit</button>

    Correct answer: Attach a ref and call inputRef.current.focus()

    React fills ref.current with the DOM node after mounting. Use refs for imperative actions like focus, scroll and measuring - not to change content.

  63. 63. What does <Button {...props} /> do?

    Correct answer: Passes each property of props as a separate prop

    Spreading is convenient for wrappers, but forwards everything, including props the child doesn't expect. Prefer explicit props where possible.

  64. 64. What do {false}, {null}, {undefined} and {0} render in JSX?

    Correct answer: Nothing for the first three, but 0 is rendered as text

    Booleans, null and undefined are ignored. Numbers (including 0) and strings are rendered, which is why {items.length && <List />} can show a stray 0.

  65. 65. What is the naming convention for props that accept event handlers?

    <SearchBox onSearch={handleSearch} />

    Correct answer: Props start with on, handlers often with handle

    Following the DOM's onClick style makes components feel familiar. The prop is just a function, so the name is up to you.

  66. 66. How does React recommend reusing UI between components?

    Correct answer: Composition: passing JSX through props and children

    Components that accept children or "slot" props (header, footer) are flexible without inheritance hierarchies. Shared logic goes into custom hooks.

  67. 67. How does defaultValue differ from value on an input?

    Correct answer: defaultValue sets only the initial value; value makes it controlled

    Uncontrolled inputs keep their value in the DOM; you read it on submit (e.g. via FormData). Changing defaultValue later has no effect.

  68. 68. How do you set the selected option of a <select> in React?

    <select value={country} onChange={(e) => setCountry(e.target.value)}>
      <option value="ua">Ukraine</option>
      <option value="pl">Poland</option>
    </select>

    Correct answer: With value or defaultValue on the <select>

    React warns if you use selected on options. multiple selects take an array as value.

  69. 69. Why does this list render nothing?

    {users.map((u) => {
      <li key={u.id}>{u.name}</li>;
    })}

    Correct answer: The block body has no return, so it returns undefined

    Use parentheses for an implicit return: users.map((u) => (<li ...>)), or write return inside the braces.

  70. 70. What is React Developer Tools useful for?

    Correct answer: Inspecting components, props, state and render timing

    The Components tab shows the tree as React sees it; the Profiler records which components rendered and why. It is a browser extension.

  71. 71. What does the React team recommend for starting a new app today?

    Correct answer: A framework like Next.js, or a build tool like Vite

    Create React App was deprecated in 2025. Frameworks add routing, data fetching and rendering strategies; Vite is a common choice for client-only apps.

  72. 72. Two <Counter /> components are rendered on the page. Do they share state?

    Correct answer: No - each rendered instance has its own state

    State belongs to a position in the tree, not to the component function. To share it, lift it to a common parent or use context/a store.

  73. 73. Why doesn't clicking <MyButton onClick={save} /> call save?

    function MyButton({ label }) {
      return <button>{label}</button>;
    }

    Correct answer: onClick is just a prop until MyButton passes it to <button>

    Only built-in DOM elements turn onClick into a listener. The component must accept the prop and forward it: <button onClick={onClick}>.

  74. 74. What type does size have in <Avatar size="40" /> versus <Avatar size={40} />?

    Correct answer: A string "40" first, a number 40 second

    Quotes pass a string literal; braces pass any JavaScript value. With TypeScript, size: number catches the mistake.

  75. 75. What does <input disabled={false} /> render?

    Correct answer: An enabled input, as React omits the false attribute

    For boolean DOM attributes, true adds the attribute and false removes it. Writing just <input disabled /> means disabled={true}.