Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Short answer: Virtualization is a technique where only the items that are visible in the viewport are rendered, while the others are not rendered until they come into view. Explain a bit more This significantly reduces t…
Short answer: Debugging performance issues can be done using several tools and strategies: Real-world example (ShopNest) Heavy product grids memoize row components so typing in the search box does not re-render every ima…
Short answer: You test React components by writing unit tests that simulate rendering, interaction, and lifecycle behavior. Key Steps: Real-world example (ShopNest) ShopNest’s storefront is React: components for ProductC…
Short answer: A unit test checks a small unit of functionality, such as a React component. Here’s how you can write a unit test: Real-world example (ShopNest) ShopNest’s storefront is React: components for ProductCard, C…
Short answer: To test component interactions like button clicks, form submissions, or other events, you can use fireEvent or user-event (for more realistic user interactions). Explain a bit more Example using fireEvent:…
Short answer: To mock API calls in tests, you can use jest.mock() to mock functions or API calls. Mocking fetch or axios: Mock fetch: global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({ dat…
Short answer: Testing async behavior often involves waiting for a component to update based on API calls or timeouts. Example code Use waitFor or findBy queries to wait for async changes. import { render, screen, waitFor…
Short answer: wait waitFor(() => screen.getByText('Loaded Data')); expect(screen.getByText('Loaded Data')).toBeInTheDocument(); }); In this case, waitFor() waits until the expected element appears in the DOM after an…
Short answer: A Higher-Order Component (HOC) is a function that takes a component and returns a new component with additional props or behavior. Explain a bit more Purpose: HOCs are used for code reuse, logic abstraction…
Short answer: A Portal provides a way to render children into a different part of the DOM outside of the parent component’s DOM hierarchy. Explain a bit more This is particularly useful for scenarios like modals, tooltip…
Short answer: An Error Boundary is a React component that catches JavaScript errors in its child components, logs those errors, and displays a fallback UI. This prevents the entire app from crashing when an error occurs…
Short answer: Controlled side effects refer to operations in React that happen as a result of state or props changes but are carefully managed, typically using React Hooks like useEffect. Explain a bit more Examples: Fet…
Short answer: Server-Side Rendering (SSR) allows React components to be rendered on the server and the resulting HTML to be sent to the client. This improves the initial loading performance and helps with SEO. SSR Proces…
Short answer: And helps with SEO. SSR Process: Real-world example (ShopNest) ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state. Say this in the interv…
Short answer: Some common build tools for React are: Real-world example (ShopNest) ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state. Say this in the…
Short answer: There are several ways to handle CSS in React applications, and each comes with its own pros and cons. Real-world example (ShopNest) ShopNest’s storefront is React: components for ProductCard, CartDrawer, a…
Short answer: CSS-in-JS libraries allow you to write CSS styles directly inside JavaScript files, enabling better component encapsulation and dynamic styling. Popular libraries include: Real-world example (ShopNest) Shop…
Short answer: Internationalization (i18n) in React can be handled using libraries that help manage translations, time formats, and currency formatting. The most common libraries are: Real-world example (ShopNest) ShopNes…
Short answer: Authentication in React apps is typically done using tokens (JWTs) and local storage to persist user sessions. Common Steps: Real-world example (ShopNest) ShopNest’s storefront is React: components for Prod…
Short answer: Managing forms in React can be tedious, but libraries like Formik and React Hook Form simplify form handling by managing state, validation, and submission. Explain a bit more Formik: Provides an easy way to…
Short answer: Side effects are operations that occur outside of the React component’s scope, such as: Fetching data from an API Setting up subscriptions Manually modifying the DOM In React, side effects are handled using…
Short answer: Infinite loops in useEffect occur when the effect continually triggers itself because the dependency array includes values that change as a result of the effect itself. Explain a bit more Common cause: If a…
Short answer: Custom hooks are a powerful way to share logic between components in a reusable and encapsulated way. Explain a bit more A custom hook is simply a JavaScript function that uses React hooks (like useState, u…
Short answer: In class components, the lifecycle is managed using methods like componentDidMount, componentDidUpdate, and componentWillUnmount. Explain a bit more With hooks, these are replaced with useEffect, which can…
Short answer: React keys help React identify which items in a list are changed, added, or removed. Keys provide a stable identity for each element, allowing React to optimize re-renders. Important: Keys should be unique…
React.js React.js Tutorial · React
Short answer: Virtualization is a technique where only the items that are visible in the viewport are rendered, while the others are not rendered until they come into view.
This significantly reduces the number of DOM nodes and boosts performance when rendering large lists. Popular libraries for virtualization in React include: react-window react-virtualized Example with react-window: import { FixedSizeList as List } from 'react-window'; function MyList({ items }) { return ( <List height={400} itemCount={items.length} itemSize={35} width={300} {({ index, style }) => ( <div style={style}>{items[index]}</div> )} </List> ); } Only the visible items will be rendered, and as the user scrolls, new items will be loaded dynamically.
When rendering cart lines, use a stable key={item.id}—not the array index—so React updates the right row after delete.
React.js React.js Tutorial · React
Short answer: Debugging performance issues can be done using several tools and strategies:
Heavy product grids memoize row components so typing in the search box does not re-render every image card unnecessarily.
React.js React.js Tutorial · React
Short answer: You test React components by writing unit tests that simulate rendering, interaction, and lifecycle behavior. Key Steps:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: A unit test checks a small unit of functionality, such as a React component. Here’s how you can write a unit test:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: To test component interactions like button clicks, form submissions, or other events, you can use fireEvent or user-event (for more realistic user interactions).
Example using fireEvent: import { render, screen, fireEvent } from '@testing-library/react'; import MyComponent from './MyComponent'; test('button click changes text', () => { render(<MyComponent />); const button = screen.getByText('Click me'); fireEvent.click(button); expect(screen.getByText('You clicked!')).toBeInTheDocument(); }); Example using user-event (better for simulating real user interactions): npm install --save-dev @testing-library/user-event import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import MyComponent from './MyComponent'; test('button click changes text', () => { render(<MyComponent />); const button = screen.getByText('Click me'); userEvent.click(button); expect(screen.getByText('You clicked!')).toBeInTheDocument(); }); user-event is better because it simulates real user actions like clicks, typing, and…
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: To mock API calls in tests, you can use jest.mock() to mock functions or API calls. Mocking fetch or axios: Mock fetch: global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({ data: 'mock data' }), }) );
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: Testing async behavior often involves waiting for a component to update based on API calls or timeouts.
Use waitFor or findBy queries to wait for async changes. import { render, screen, waitFor } from '@testing-library/react'; import MyComponent from './MyComponent'; test('loads data asynchronously', async () => { render(<MyComponent />); // Wait for the element that should appear after the async call await waitFor(() => screen.getByText('Loaded Data')); expect(screen.getByText('Loaded Data')).toBeInTheDocument(); }); In this case, waitFor() waits until the expected element appears in the DOM after an async operation completes.
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: wait waitFor(() => screen.getByText('Loaded Data')); expect(screen.getByText('Loaded Data')).toBeInTheDocument(); }); In this case, waitFor() waits until the expected element appears in the DOM after an sync operation completes.
wait waitFor(() => screen.getByText('Loaded Data')); expect(screen.getByText('Loaded Data')).toBeInTheDocument(); }); In this case, waitFor() waits until the expected element appears in the DOM after an sync operation completes. wait waitFor(() => screen.getByText('Loaded Data')); expect(screen.getByText('Loaded Data')).toBeInTheDocument(); }); In this case, waitFor() waits until the expected element appears in the DOM after an sync operation completes.
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: A Higher-Order Component (HOC) is a function that takes a component and returns a new component with additional props or behavior.
Purpose: HOCs are used for code reuse, logic abstraction, and enhancing components with common functionality (e.g., authentication, data fetching, etc.). How it works: HOCs are like decorators that wrap a component and add extra logic before rendering the component. Example: function withLoading(Component) { return function WithLoading(props) {
if (props.isLoading) {
return <div>Loading...</div>;
}
return <Component {...props} />; }; }
const MyComponent = ({ data }) => <div>{data}</div>;
const MyComponentWithLoading = withLoading(MyComponent); In this example, withLoading is a higher-order component that adds loading state to MyComponent.
React.js React.js Tutorial · React
Short answer: A Portal provides a way to render children into a different part of the DOM outside of the parent component’s DOM hierarchy.
This is particularly useful for scenarios like modals, tooltips, or popups that need to visually break out of their parent component but still maintain their React component state. When to use: When you need to render content outside the DOM hierarchy of a parent, without losing the React component context (e.g., for modals, overlays, etc.).
import React from 'react'; import ReactDOM from 'react-dom'; function Modal() { return ReactDOM.createPortal( <div className="modal">This is a modal</div>, document.getElementById('modal-root') // Renders outside the normal DOM tree ); } export default Modal; In this case, the modal is rendered inside a specific part of the DOM (modal-root) even though it is a child of the Modal component.
React.js React.js Tutorial · React
Short answer: An Error Boundary is a React component that catches JavaScript errors in its child components, logs those errors, and displays a fallback UI. This prevents the entire app from crashing when an error occurs in a part of the component tree. Usage:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: Controlled side effects refer to operations in React that happen as a result of state or props changes but are carefully managed, typically using React Hooks like useEffect.
Examples: Fetching data, subscribing to an event, manually updating the DOM, etc. Controlled: The side effect is triggered in response to specific state changes and cleaned up appropriately. Example of controlled side effect with useEffect: import React, { useState, useEffect } from 'react'; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { const result = await fetch('/api/data'); const json = await result.json(); setData(json); }; fetchData(); }, []); // Only runs once when the component is mounted return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; } Here, useEffect handles the side effect of fetching data when the component mounts, and the state is updated with the fetched data.
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: Server-Side Rendering (SSR) allows React components to be rendered on the server and the resulting HTML to be sent to the client. This improves the initial loading performance and helps with SEO. SSR Process:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: And helps with SEO. SSR Process:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: Some common build tools for React are:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: There are several ways to handle CSS in React applications, and each comes with its own pros and cons.
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: CSS-in-JS libraries allow you to write CSS styles directly inside JavaScript files, enabling better component encapsulation and dynamic styling. Popular libraries include:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: Internationalization (i18n) in React can be handled using libraries that help manage translations, time formats, and currency formatting. The most common libraries are:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: Authentication in React apps is typically done using tokens (JWTs) and local storage to persist user sessions. Common Steps:
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
React.js React.js Tutorial · React
Short answer: Managing forms in React can be tedious, but libraries like Formik and React Hook Form simplify form handling by managing state, validation, and submission.
Formik: Provides an easy way to manage form state, validation, and submission. Supports validation using schemas (e.g., Yup). Example with Formik: import { Formik, Field, Form } from 'formik'; function MyForm() { return ( <Formik initialValues={{ name: '', email: '' }} onSubmit={(values) => console.log(values)} <Form> <Field name="name" /> <Field name="email" /> <button type="submit">Submit</button> </Form> </Formik> ); } React Hook Form: A lightweight alternative to Formik that uses React hooks to handle form state. It’s more performance-oriented due to less re-rendering. Example with React Hook Form: import { useForm } from 'react-hook-form'; function MyForm() { const { register, handleSubmit } = useForm();
const onSubmit = (data) => console.log(data);
return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('name')} /> <input {...register('email')} /> <button type="submit">Submit</button> </form> ); } Both libraries significantly reduce boilerplate and handle common issues like validation and form state management. Hooks Deep Dive
React.js React.js Tutorial · React
Short answer: Side effects are operations that occur outside of the React component’s scope, such as: Fetching data from an API Setting up subscriptions Manually modifying the DOM In React, side effects are handled using the useEffect hook. Basic
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only run when `count` changes return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); } useEffect allows you to perform side effects in function components. The second argument, the dependency array, specifies when to run the effect. If the array is empty, the effect runs only once after the initial render (like componentDidMount).
ShopNest’s cart icon uses useState for count and useEffect to load the cart once on mount.
React.js React.js Tutorial · React
Short answer: Infinite loops in useEffect occur when the effect continually triggers itself because the dependency array includes values that change as a result of the effect itself.
Common cause: If a value inside useEffect is being updated, and it's in the dependency array, React will keep rerunning the effect. How to avoid: Use an empty dependency array ([]) if the effect should run only once. Be selective with dependencies to avoid unnecessary re-renders.
useEffect(() => { // Perform API call or other side effects fetchData(); }, []); // No dependencies, effect runs only once If the dependency list has state values or props that change inside the effect, React will rerun it every time those values change. Be mindful of that!
ShopNest’s cart icon uses useState for count and useEffect to load the cart once on mount.
React.js React.js Tutorial · React
Short answer: Custom hooks are a powerful way to share logic between components in a reusable and encapsulated way.
A custom hook is simply a JavaScript function that uses React hooks (like useState, useEffect, etc.). Example of a custom hook: // useLocalStorage.js import { useState } from 'react'; function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue; }); const setValue = (value) => { setStoredValue(value); localStorage.setItem(key, JSON.stringify(value)); }; return [storedValue, setValue];
} export default useLocalStorage; You can then use this custom hook in any component: import useLocalStorage from './useLocalStorage'; function App() { const [name, setName] = useLocalStorage('name', 'John');
return ( <div> <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter your name" /> </div> ); } Custom hooks allow for reusable logic (like managing form state, fetching data, etc.) and encapsulation of behavior in a way that doesn't require repeated code.
ShopNest’s cart icon uses useState for count and useEffect to load the cart once on mount.
React.js React.js Tutorial · React
Short answer: In class components, the lifecycle is managed using methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
With hooks, these are replaced with useEffect, which can mimic any lifecycle behavior. Lifecycle Mapping: componentDidMount: Use useEffect with an empty dependency array ([]). componentDidUpdate: Use useEffect with dependencies. componentWillUnmount: Return a cleanup function inside useEffect.
useEffect(() => { // Equivalent to componentDidMount and componentDidUpdate console.log("Component mounted or updated"); return () => { // Equivalent to componentWillUnmount console.log("Cleanup before component unmount"); }; }, [dependencies]); // Will run on mount and update based on dependencies
ShopNest’s cart icon uses useState for count and useEffect to load the cart once on mount.
React.js React.js Tutorial · React
Short answer: React keys help React identify which items in a list are changed, added, or removed. Keys provide a stable identity for each element, allowing React to optimize re-renders. Important: Keys should be unique for each sibling component. Why important: Without keys, React has to re-render all list items when the list changes, which can be inefficient.
const items = ['apple', 'banana', 'cherry']; return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); Tip: It’s better to use a unique identifier (e.g., id) as a key instead of using index if the list can change order or content dynamically.
When rendering cart lines, use a stable key={item.id}—not the array index—so React updates the right row after delete.