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.
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. 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. 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 likejsx("h1", { className: "t", children: "Hi" }), which returns a description object. Browsers don't understand JSX, and React doesn't useinnerHTML- that's why strings in JSX are escaped automatically.4. How do you set a CSS class on an element in JSX?
Correct answer:
<div className="box">JSX is closer to JavaScript, and
classis a reserved word, so attributes are named like DOM properties:className,htmlForinstead offor,tabIndex,onClick.data-*andaria-*attributes are written as in HTML.5. Why can't you write
{if (isAdmin) { <Admin /> }}inside JSX?Correct answer: Only expressions are allowed in curly braces, and
ifis a statementInside
{}you can put any JS expression that produces a value: a variable, a function call, a ternarycond ? a : b,cond && a. Statements (if,for) are used outside JSX - beforereturnor in a separate function. React has no<If>component.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 elementcard, while<Card />becomes a call to your component. The declaration form (function or arrow) and the export style don't matter.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 akey, otherwise you get a warning.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. 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 callsprops.onChange(value). Mutating props won't re-render the parent, and function components have no access to the parent instance.10. What is
childrenin React?Correct answer: A prop with the content passed between the component's tags
<Card><h2>Title</h2></Card>passes the<h2>inprops.children. It's the basis of composition: wrappers, layouts and modals accept arbitrary content.childrencan be a string, an element, an array or a function (the render props pattern).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. What does
console.logprint after a click?const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); console.log(count); }Correct answer:
0State within a render is a "snapshot".
setCountschedules a new render, but thecountvariable 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. What will
countbe after one click if the initial value is 0?function handleClick() { setCount(count + 1); setCount(count + 1); setCount(count + 1); }Correct answer:
1All three calls see the same snapshot
count = 0and queue the value1three 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. 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 likememo.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.
pushmutates 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. Which value is best for
keyin a list?Correct answer: A stable unique identifier from the data, such as
idkeyhelps 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. What is rendered if
items = []?<div>{items.length && <List items={items} />}</div>Correct answer: The digit
0is rendered0 && xreturns0, and React renders numbers as text (unlikefalse,null,undefined). Write an explicit boolean condition:items.length > 0 && ...or a ternaryitems.length ? <List /> : null.18. What's wrong with
<button onClick={handleClick()}>?Correct answer: The function is called immediately during render, not on click
onClickneeds a function, not the result of calling it. Correct:onClick={handleClick}, oronClick={() => handleClick(id)}if you need arguments. IfhandleClickchanges state, calling it during render causes an infinite loop.19. How do you cancel the default form submission behavior in React?
Correct answer: Call
e.preventDefault()in theonSubmithandlerIn 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 withe.stopPropagation().20. What is a controlled input?
Correct answer: A field whose value is stored in state:
value+onChangeIn a controlled field, state is the source of truth:
value={text}andonChange={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 viareforFormData).21. React warns: "You provided a
valueprop to a form field without anonChangehandler". What happened?Correct answer: The field became read-only:
valueis set butonChangeisn'tIf you set
valuewithoutonChange, React resets the field to that value on every render, and the user can't type. Fixes: addonChange, usedefaultValuefor an uncontrolled field, or setreadOnlyexplicitly.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. 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. 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. 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 wheneveraorbchanges (compared viaObject.is).26. When is the function returned from
useEffectcalled?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. How does
useRefdiffer fromuseState?Correct answer: Changing
ref.currentdoesn't trigger a re-renderuseRefkeeps 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. 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 changesReact 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. Why must a custom hook's name start with
use?Correct answer: That's how the linter and React know it contains hooks
The
useprefix is a convention thateslint-plugin-react-hooksand the React Compiler rely on. By itself it doesn't memoize anything. A function with no hooks inside shouldn't be nameduse...- it's a regular utility.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. How do you set an inline style in JSX?
Correct answer:
style={{ color: "red", fontSize: 14 }}styletakes 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. What steps are needed to pass data via Context?
Correct answer:
createContext→ a provider withvalue→useContextin a descendantconst ThemeContext = createContext('light')→<ThemeContext value={theme}>(in React 19 you can omit.Provider) →useContext(ThemeContext)in any descendant. Whenvaluechanges, all components reading this context re-render.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. 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. What is
React.lazyused 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. What does
React.lazyneed 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 itsfallback. Declarelazyat module level, not inside a component - otherwise every render creates a new component and loses state. The module must have adefaultexport.37. Why does
lazy(() => import('./Chart'))fail ifChart.tsxhas onlyexport function Chart?Correct answer:
lazyexpects a module with adefaultexportThe promise from
import()must resolve to an object with adefaultfield. For a named export, map it:lazy(() => import('./Chart').then(m => ({ default: m.Chart }))). TypeScript and function components are fully supported.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. How do you attach an app to a DOM element in React 18+?
Correct answer:
createRoot(el).render(<App />)createRootfromreact-dom/clientenables React 18+ concurrent features.ReactDOM.renderis deprecated and removed in React 19. To hydrate server-rendered HTML, usehydrateRoot. Frameworks like Next.js do this automatically.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. How do you render a list of users from the
usersarray?Correct answer:
{users.map(u => <li key={u.id}>{u.name}</li>)}mapreturns a new array of elements that React renders.forEachreturnsundefined, so nothing appears.foris a statement and can't be written inside{}. And don't forgetkey.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. What's required of a reducer in classic Redux (without Immer)?
Correct answer: To be pure and return new state without mutations
(state, action) => newStatewith 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. What does
configureStorefrom Redux Toolkit do?Correct answer: Creates a store with sensible defaults: thunk, DevTools
configureStore({ reducer: { todos: todosReducer } })combines reducers, adds theredux-thunkmiddleware, 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. What are
useSelectoranduseDispatchfor?Correct answer:
useSelectorreads data from the store,useDispatchgives youdispatchconst 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 versionsuseAppSelectoranduseAppDispatch.46. What does
createSlicegenerate?Correct answer: A reducer and action creators for each case reducer
createSlice({ name: 'todos', initialState, reducers: { added(state, action) {...} } })returnstodosSlice.reducerandtodosSlice.actions.addedwith the type'todos/added'. This removes classic Redux boilerplate with type constants and switch.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. What must you pass to
useQuery?Correct answer:
queryKeyandqueryFnuseQuery({ 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 whenidchanges.queryFnis any function returning a promise; the library isn't tied tofetch.49. How do
isPendingandisFetchingdiffer in TanStack Query v5?Correct answer:
isPending- no data yet,isFetching- any request is in flightisPending(statuspending) means there's no data in the cache yet - show a skeleton.isFetchingis true for every request, including background refetches of existing data - a small indicator fits here. In v4,isLoadingwas used instead ofisPending.50. What must you do before using
useQueryin an app?Correct answer: Create a
QueryClientand wrap the app in its providerQueryClientholds the cache and default settings, and the provider makes it available to hooks. Create the client once (outside a component or viauseState), otherwise the cache resets on every render. TanStack Query doesn't need Redux.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.defaultPropsfor function components was deprecated and removed in React 19.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 beforereturn.53. What should a component return to render nothing?
Correct answer:
nullReturning
nullrenders nothing but the component still exists (its hooks and state live on). Since React 18, returningundefinedis also allowed butnullis clearer.54. Which attribute links a
<label>to an input in JSX?Correct answer:
htmlForLike
className,htmlForavoids a reserved JavaScript word. Wrapping the input inside<label>also links them without an id.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. 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. When does
onChangefire on a text input in React?Correct answer: On every keystroke, like the DOM
inputeventReact normalizes
onChangeto fire on each change, unlike the nativechangeevent that waits for blur. That makes controlled inputs possible.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)}onClickexpects a function.remove(t.id)would run during render and pass its return value as the handler.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 handlerReact events bubble like DOM events (except
onScroll). Returningfalsedoesn't stop anything in React; usestopPropagationorpreventDefaultexplicitly.60. Must
keyvalues 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.
keyisn't passed to the component as a prop; pass the id separately if the child needs it.61. How do you add a
keywhen 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. ImportFragmentfromreactwhen you need a key.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.currentwith the DOM node after mounting. Use refs for imperative actions like focus, scroll and measuring - not to change content.63. What does
<Button {...props} />do?Correct answer: Passes each property of
propsas a separate propSpreading is convenient for wrappers, but forwards everything, including props the child doesn't expect. Prefer explicit props where possible.
64. What do
{false},{null},{undefined}and{0}render in JSX?Correct answer: Nothing for the first three, but
0is rendered as textBooleans,
nullandundefinedare ignored. Numbers (including0) and strings are rendered, which is why{items.length && <List />}can show a stray 0.65. What is the naming convention for props that accept event handlers?
<SearchBox onSearch={handleSearch} />Correct answer: Props start with
on, handlers often withhandleFollowing the DOM's
onClickstyle makes components feel familiar. The prop is just a function, so the name is up to you.66. How does React recommend reusing UI between components?
Correct answer: Composition: passing JSX through props and
childrenComponents that accept
childrenor "slot" props (header,footer) are flexible without inheritance hierarchies. Shared logic goes into custom hooks.67. How does
defaultValuediffer fromvalueon an input?Correct answer:
defaultValuesets only the initial value;valuemakes it controlledUncontrolled inputs keep their value in the DOM; you read it on submit (e.g. via
FormData). ChangingdefaultValuelater has no effect.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
valueordefaultValueon the<select>React warns if you use
selectedon options.multipleselects take an array asvalue.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 returnsundefinedUse parentheses for an implicit return:
users.map((u) => (<li ...>)), or writereturninside the braces.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. 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. 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. Why doesn't clicking
<MyButton onClick={save} />callsave?function MyButton({ label }) { return <button>{label}</button>; }Correct answer:
onClickis just a prop untilMyButtonpasses it to<button>Only built-in DOM elements turn
onClickinto a listener. The component must accept the prop and forward it:<button onClick={onClick}>.74. What type does
sizehave in<Avatar size="40" />versus<Avatar size={40} />?Correct answer: A string
"40"first, a number40secondQuotes pass a string literal; braces pass any JavaScript value. With TypeScript,
size: numbercatches the mistake.75. What does
<input disabled={false} />render?Correct answer: An enabled input, as React omits the
falseattributeFor boolean DOM attributes,
trueadds the attribute andfalseremoves it. Writing just<input disabled />meansdisabled={true}.