React

Top 20 React Interview Questions and Answers with Examples

Prepare for React interviews with 20 questions covering components, JSX, props, state, hooks, useEffect, context, routing, forms, performance and Redux Toolkit.

This React interview preparation guide focuses on understanding each concept, explaining when it matters, and supporting your answer with a practical example. Use it as a revision checklist and practise explaining the ideas in your own words.

How to use this guide: Try answering each question aloud before opening the explanation. Then adapt the example to a real application or project you have worked on.

1. What is React?

Answer: React is a JavaScript library for building user interfaces from reusable components. Components describe what the UI should look like for a given state; React updates the rendered interface when that state changes. React can be used for single-page applications, server-rendered applications and embedded interactive sections. It focuses on the UI layer, so routing, data fetching and state management are often provided by additional libraries or framework features.

Example

A page can be composed from independent components such as Header, ProductList and CartSummary.

2. What is a React component?

Answer: A component is a reusable piece of UI. Modern React components are commonly JavaScript functions that accept props and return JSX. Keep components focused, derive values from props and state where possible, and move shared behaviour into custom hooks. Component names begin with a capital letter so JSX treats them as user-defined components rather than built-in HTML tags.

Example

function Greeting({ name }) {
  return <h2>Welcome, {name}!</h2>;
}

3. What is JSX?

Answer: JSX is a syntax extension that lets developers describe UI using markup-like expressions inside JavaScript. It is transformed by the build tool into JavaScript calls that create React elements. JSX expressions use curly braces for JavaScript values, class names use className, and elements must be properly closed. JSX is optional, but it is the standard way most React projects express UI.

Example

const title = "Interview preparation";
return <h1 className="page-title">{title}</h1>;

4. What is the difference between props and state?

Answer: Props are inputs passed from a parent component and should be treated as read-only by the receiving component. State is data a component manages over time; updating state schedules a re-render. Props allow parent-to-child communication, while state handles values that change due to user actions, network responses or other events. Avoid copying props into state unless you intentionally need an independent snapshot.

Example

function Counter({ start }) {
  const [count, setCount] = useState(start);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

5. What are React Hooks?

Answer: Hooks are functions that let function components use React features such as state, context, refs and effects. Built-in hooks include useState, useEffect, useContext, useRef, useMemo and useCallback. Hooks must be called at the top level of a React component or custom hook, not inside loops or conditions, so React can preserve their call order between renders.

Example

const [isOpen, setIsOpen] = useState(false);
const theme = useContext(ThemeContext);

6. How does useState work?

Answer: useState returns the current state value and a setter function. Calling the setter schedules a re-render; it does not mutate the current render’s variable. When the new value depends on the previous value, use the functional updater form so queued updates are calculated from the latest state. React may batch updates for performance.

Example

const [count, setCount] = useState(0);
setCount(previous => previous + 1);

7. What is useEffect used for?

Answer: useEffect synchronises a component with external systems after rendering, such as browser APIs, subscriptions or network activity. It is not needed for every calculation or event handler. The dependency array controls when the effect re-runs, and an optional cleanup function runs before the effect is repeated and when the component unmounts. For data fetching, handle cancellation or stale responses appropriately.

Example

useEffect(() => {
  const handler = () => setWidth(window.innerWidth);
  window.addEventListener("resize", handler);
  return () => window.removeEventListener("resize", handler);
}, []);

8. How does the useEffect dependency array work?

Answer: With no dependency array, an effect runs after every committed render. With an empty array, it runs after the initial mount and cleans up on unmount. With dependencies, it runs after the initial mount and whenever one of those values changes according to Object.is comparison. Include every reactive value used by the effect; do not omit dependencies just to suppress reruns.

Example

useEffect(() => {
  document.title = `Cart (${itemCount})`;
}, [itemCount]);

9. What is the difference between useMemo and useCallback?

Answer: useMemo memoises a calculated value between renders when dependencies have not changed. useCallback memoises a function reference. They can help when expensive calculations or referential equality matter, for example with memoised child components. They are not default requirements; memoisation adds complexity and should be guided by profiling or a clear identity requirement.

Example

const total = useMemo(() => items.reduce((sum, x) => sum + x.price, 0), [items]);
const handleSave = useCallback(() => save(id), [id]);

10. What is useRef and when would you use it?

Answer: useRef returns a mutable object whose current property persists between renders without causing a re-render when changed. It is useful for referencing DOM elements, storing timer IDs or retaining a value that does not affect displayed output. Use state instead when a change should update the UI. Mutating a ref during rendering should be avoided unless it is part of a supported initialisation pattern.

Example

const inputRef = useRef(null);
function focusInput() { inputRef.current?.focus(); }
return <input ref={inputRef} />;

11. Why are keys important when rendering lists?

Answer: Keys help React match items between renders so it can preserve the correct component state and update only what changed. Use a stable unique identifier from the data. Array indexes can cause bugs when items are inserted, removed or reordered because the same index may now represent a different item. Keys only need to be unique among siblings.

Example

{users.map(user => (
  <UserRow key={user.id} user={user} />
))}

12. What is the difference between controlled and uncontrolled components?

Answer: A controlled form element gets its value from React state and updates that state through an event handler. An uncontrolled element keeps its current value in the DOM and can be read with a ref or form submission. Controlled inputs make validation and conditional UI easier; uncontrolled inputs can be simpler for small forms or when integrating with non-React code.

Example

const [email, setEmail] = useState("");
<input value={email} onChange={e => setEmail(e.target.value)} />

13. What is lifting state up?

Answer: Lifting state up means moving shared state to the closest common parent of components that need to read or update it. The parent passes values and callbacks down as props. This creates a single source of truth and keeps sibling components in sync. If the tree becomes too deeply nested, context or a dedicated state library may be more suitable.

Example

A product list and cart summary can share cart items through their parent page rather than maintaining separate copies.

14. What is React Context?

Answer: Context lets a component provide a value to descendants without passing props through every intermediate component. It is useful for relatively stable cross-tree values such as theme, locale or authenticated-user information. Context updates can cause consumers to re-render, so split unrelated contexts and memoise provider values where appropriate. Context is not automatically a complete replacement for every state-management library.

Example

const ThemeContext = createContext("light");
<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>

15. What is useReducer and when is it useful?

Answer: useReducer manages state through a reducer function that receives the current state and an action and returns the next state. It is useful when state transitions are complex, involve several related fields or depend on multiple action types. It keeps update logic in one place and can make transitions easier to test. For a simple independent value, useState is usually clearer.

Example

function reducer(state, action) {
  if (action.type === "increment") return { count: state.count + 1 };
  return state;
}
const [state, dispatch] = useReducer(reducer, { count: 0 });

16. How does routing work in a React application?

Answer: Client-side routing maps browser locations to components without a full page reload. A routing library such as React Router manages route definitions, parameters, nested layouts and navigation. A production server must also be configured to serve the application entry point for valid client-side routes. Protect sensitive data on the server; hiding a route in the client is not access control.

Example

<Routes>
  <Route path="/products/:id" element={<ProductPage />} />
</Routes>

17. What is React.memo?

Answer: React.memo is a higher-order component that can skip rendering a function component when its props have not changed according to a shallow comparison by default. It can help when a component renders often with the same props and its render is expensive. It does not stop updates caused by the component’s own state or consumed context. Profile before applying it broadly.

Example

const UserCard = memo(function UserCard({ user }) {
  return <div>{user.name}</div>;
});

18. What is Redux Toolkit and why is it preferred for Redux?

Answer: Redux Toolkit is the recommended way to write Redux logic. It reduces boilerplate with configureStore and createSlice, provides safe immutable update patterns through Immer, and includes good defaults such as thunk middleware and development checks. It is useful for shared application state with complex updates; local UI state can remain in React components.

Example

const counterSlice = createSlice({
  name: "counter", initialState: { value: 0 },
  reducers: { increment: state => { state.value += 1; } }
});

19. How do you fetch data in React?

Answer: Data can be fetched in an effect for a simple component, but real applications often use a server-state library or framework data APIs to handle caching, retries, loading states and stale responses. Always model loading, success and error states. Avoid updating an unmounted component or letting an older request overwrite a newer result; use AbortController or a suitable query library.

Example

useEffect(() => {
  const controller = new AbortController();
  fetch("/api/products", { signal: controller.signal })
    .then(r => { if (!r.ok) throw new Error("Request failed"); return r.json(); })
    .then(setProducts).catch(e => { if (e.name !== "AbortError") setError(e); });
  return () => controller.abort();
}, []);

20. How do lazy loading and Suspense help performance?

Answer: Lazy loading delays loading a component’s code until it is needed, which can reduce the initial JavaScript bundle. Suspense displays a fallback while a supported lazy component or data source is not ready. Use route-level code splitting for large pages and provide useful loading feedback. Measure the initial bundle and navigation experience rather than splitting every tiny component.

Example

const ReportsPage = lazy(() => import("./ReportsPage"));
<Suspense fallback={<p>Loading reports…</p>}>
  <ReportsPage />
</Suspense>

How to prepare for your interview

Do not memorise definitions word for word. Practise explaining the concept in your own words, describe when you would use it, and mention one trade-off or common mistake. For coding and database topics, write the example yourself and test the edge cases.

Use this guide as a revision checklist, then review the topics you find difficult in more depth. Interview discussions often move from fundamentals to project decisions, debugging and performance scenarios.

Keep learning with DotNetRevision. Explore the ebook library for structured study guides, interview preparation and practical professional-development resources.

Browse DotNetRevision ebooks →

CONTINUE LEARNING

More interview preparation guides

Explore related C#, .NET, EF Core, React, TypeScript and SQL Server topics.

Browse all interview guides →