Tuesday, 21 April 2026

React Set 4 - Interview Happy

 Here are all the React interview questions and answers from the transcript:


CHAPTER 1 — BASICS

Q1. What is React? What is the role of React in software development? React is an open-source JavaScript library used for building user interfaces. In a typical web architecture, the frontend server handles what the user sees. React simplifies the creation of single-page applications by using reusable components. Although we already have HTML, CSS, and JavaScript, React simplifies the creation of complex UI applications.


Q2. What are the key features of React? The seven key features are:

  1. Virtual DOM
  2. Component-based architecture
  3. Reusability and composition
  4. JSX (JavaScript XML)
  5. Declarative syntax
  6. Community and ecosystem
  7. React Hooks

Q3. What is DOM? What is the difference between HTML and DOM? DOM stands for Document Object Model. It represents the web page as a tree-like structure that allows JavaScript to dynamically access and manipulate the content and structure of a web page. HTML is just a markup language for reading and writing purposes. In reality, the browser's memory works with the DOM tree. When a user adds or updates an element via JavaScript, a node is added or modified in the DOM tree, which is then converted back to HTML and displayed.


Q4. What is Virtual DOM? What is the difference between DOM and Virtual DOM? Virtual DOM is a concept specific to React (developed by Facebook) to improve application speed. The problem with the real DOM is that even a small change causes the entire page layout to re-render. React solves this by creating an exact copy of the real DOM called the Virtual DOM. When the user interacts, changes are made to the Virtual DOM only. React algorithms then compare (diff) the Virtual DOM with the real DOM and update only the changed parts in the real DOM. This process is called reconciliation.

Differences:

  1. DOM is real and browser-native; Virtual DOM is React-specific.
  2. DOM re-renders the whole page on change; Virtual DOM updates only changed parts.
  3. Virtual DOM makes the web page faster to load.
  4. Virtual DOM is a two-step process (virtual → real) but overall faster.

Q5. What are React components? What are the main elements of a component? In React, a component is a reusable building block for creating user interfaces. A web page is made up of multiple sections (header, menu, footer, etc.) — each is a component. The main elements of a component are:

  1. Import statement
  2. A function or class defining the component logic
  3. A return statement with JSX
  4. An export statement to make the component available in other files

Q6. What is a Single Page Application (SPA)? A Single Page Application is a web application that has only one single web page. When a user performs actions, content is dynamically updated without refreshing or loading a new page. React makes it simple to build SPAs using reusable components. Example: YouTube — the whole page never reloads, only the content/components update.


Q7. What are the five advantages of React?

  1. Component-based architecture — allows creation of reusable components, making development faster and more efficient.
  2. Cross-platform and open-source — free to use, works for web, mobile, and desktop platforms.
  3. Lightweight and fast — due to the Virtual DOM concept.
  4. Large community and ecosystem — maximum jobs, forums, and support available.
  5. Easy UI testing — React libraries make testing the UI straightforward.

Q8. What are the disadvantages of React? React is not a good choice for very simple, mostly static websites. For small applications, the learning curve, project setup, downloading libraries, and planning involved in React can be an overhead. For such cases, plain HTML, CSS, and JavaScript are more appropriate.


Q9. What is the role of JSX in React? JSX stands for JavaScript XML — it looks like HTML/XML but is converted to JavaScript. Three key points:

  1. JSX improves code readability and writability — simpler than writing raw React.createElement() calls.
  2. Browsers only understand JavaScript — Babel converts JSX to JavaScript.
  3. JSX makes development easier — it is simple to read and write.

Q10. What is the difference between declarative and imperative syntax? Declarative syntax (JSX/React): code focuses on what the output should look like. You return HTML-like JSX and the result is self-explanatory — it does not focus on step-by-step programming. Imperative syntax (pure JavaScript): focuses on step-by-step instructions — create element, assign text, append to DOM, etc. React's declarative syntax is a key feature that makes React code simpler and more readable.


CHAPTER 2 — BASICS (CONTINUED)

Q11. What is the arrow function expression in JSX? Arrow function expression is a combination of arrow function syntax and function expression. Instead of using the function keyword and a function name, you assign an arrow function to a variable. Example: const MyComponent = (props) => { return <div/>; }. The function name is not needed because you use the variable name to call or export it. This is now the recommended approach for declaring React components.


Q12. How to set up a React project? Five steps:

  1. Install Node.js.
  2. Install a code editor like VS Code.
  3. Open terminal and run: npx create-react-app my-app
  4. Open the created folder in VS Code.
  5. Run npm start in the terminal — the browser auto-loads your first React app.

Q13. How does the React app load and display components in the browser? Flow:

  1. User opens browser → request goes to React server → index.html is returned (the single HTML page).
  2. index.html loads the React libraries, which load index.js (the JavaScript entry point).
  3. index.js calls the App component (root component).
  4. The App root component replaces the root element (div#root) in index.html with all child components.
  5. The result is displayed in the browser.

Q14. What is the difference between React and Angular? Similarities: both used to create SPA web applications using components.

Differences:

  1. React is a JavaScript library; Angular is a complete UI framework.
  2. React uses Virtual DOM (faster); Angular uses real DOM.
  3. React is lightweight and smaller in size; Angular is bigger.
  4. React depends on external libraries for complex features (more code to write); Angular has built-in routing, forms, HTTP, etc.
  5. React is simpler to learn and more popular; Angular is slightly harder (requires TypeScript, OOP concepts).

Q15. What are other popular JS frameworks other than React? Popular frontend frameworks/libraries besides React: Angular, Vue.js, AngularJS, Backbone.js, Ember.js. React is currently the most popular.


Q16. Whether React is a library or a framework? What is the difference? React is commonly referred to as a JavaScript library. A library provides reusable functions that you import and use — you control the structure. A framework is a complete package that defines its own rules and structure that developers must follow (e.g., Angular). React is a library, though it is increasingly doing things a framework can do.


Q17. How does React provide reusability and composition? React provides both through its component-based architecture. Reusability: once a component is created, it can be reused in different parts of the application and across multiple projects. Composition: creating new, larger components by combining existing small components. The advantage is that components can be created independently by different developers, and changes to one component do not impact the rest of the application.


Q18. What are state, stateless, stateful, and state management? State refers to the current data of a component (e.g., a count variable set to 0). Stateless: a component that cannot render state changes in the UI — even if data updates, the UI does not reflect it. Stateful (state management): when a user performs an action, the React application updates and renders the data/state in the UI immediately. To make a component stateful, use React Hooks or component lifecycle methods.


Q19. What are props in JSX? Props (short for properties) are a way to pass data from a parent component to a child component. In the parent, data is passed as attributes on the child component tag. In the child, it is received via the props parameter and accessed as props.name, props.purpose, etc.


CHAPTER 3 — FILES AND FOLDERS

Q20. What is npm? What is the role of the node_modules folder? npm (Node Package Manager) is used to manage dependencies for a React project, including the React library itself. It downloads and installs all required libraries at once. The node_modules folder contains all the dependencies of the project including the React libraries. You should never modify this folder manually.


Q21. What is the role of the public folder in React? The public folder contains static assets served directly to the user's browser, such as images, fonts, and the index.html file. Static means no user interaction, no JavaScript logic, no API data fetching — just fixed content like favicon, index.html, and images.


Q22. What is the role of the src folder in React? The src (source) folder is where all the source code developed by the developer is placed. It is the most important folder from a developer's point of view. All components and dynamic application logic live here. It is responsible for the dynamic changes in the web application.


Q23. What is the role of the index.html page in React? index.html is the single page in a React single-page application. It is a static HTML file inside the public folder. When a user opens the React website, this is the first page that loads. It contains a <div id="root"> which is replaced dynamically by the components from index.js. The title and meta tags remain as-is; only the root div is replaced.


Q24. What is the role of the index.js file in React? index.js is the JavaScript entry point for the React application. It imports the ReactDOM library from react-dom/client. It uses ReactDOM.createRoot() to get a reference to the root element from index.html. It then calls .render() to render the App component in place of the root element. Definition: index.js replaces the root element of index.html with the newly rendered component using the ReactDOM library.


Q25. What is the role of the App.js file in React? App.js contains the root component (App) of the React application. The App component acts as a container for all child components — it is like the parent of all components. Three key points:

  1. App.js contains the root App component.
  2. App component is a container for all child components.
  3. App.js defines the structure, layout, and routing of the application.

Q26. What is the role of the function and return statements inside App.js? The function keyword defines a JavaScript function that represents the React component. It is a placeholder containing all the logic of the component. The function takes props as arguments and returns JSX. The return statement returns the JSX elements that will be displayed in the browser. Without a return, nothing is rendered to the DOM.


Q27. Can we have a function without a return statement inside App.js? Yes. A function without a return statement is valid — the component renders nothing in the UI. A common real-world use case is for logging or error-tracking components that only perform side effects (like console.log) without rendering any element.


Q28. What is the role of 'export default' inside App.js? The export default statement makes the component available for import in other files. If you remove it, the import statement in other files (like index.js) will fail and throw an error because the component is no longer available for external use.


Q29. Does the file name and component name have to be the same in React? No, they can be different. However, it is not recommended — keeping them the same is a best practice for easier code organization and readability.


CHAPTER 4 — JSX

Q30. What are the advantages of JSX?

  1. Improved readability and writability — simpler than raw JavaScript React code.
  2. Better error checking / type safety — JSX shows errors (red underlines) in the editor in advance; raw JavaScript does not.
  3. Supports JavaScript expressions — you can embed JS expressions inside curly braces {}.
  4. Improved performance.
  5. Code reusability.

Q31. What is Babel? Babel is a library (included in node_modules, installed by npm) that transpiles JSX syntax into regular JavaScript which browsers can understand. Browsers like Chrome and Edge cannot read JSX directly — Babel converts it to valid JavaScript first. Definition: Babel is a transpiler used in React to convert JSX to JavaScript.


Q32. What is the role of fragments in React? In JSX, all elements must be enclosed inside a common root/parent element. If you have sibling elements without a parent, you get a compilation error. Wrapping in a div adds an unwanted DOM node and can break layout. The proper solution is to use React Fragment: <React.Fragment>...</React.Fragment> or the shorthand <>...</>. Fragments group children without adding any extra nodes to the DOM. Definition: a fragment is a way to group a list of children without adding extra nodes to the DOM.


Q33. What is a spread operator in JSX? The spread operator (...) is used to expand or spread an array or object. In React, when passing multiple properties from a parent to a child component, you can create a props object and use the spread operator to pass all properties at once: <ChildComponent {...propsObject} />. The child accesses them the same way as normal props.


Q34. What are the types of conditional rendering in JSX? Four types:

  1. if/else — traditional conditional, good for multiple statements.
  2. Ternary operator — single-line: condition ? 'true' : 'false'.
  3. AND operator (&&) — returns the statement if condition is true; returns null if false (no else option).
  4. Switch statement — for multiple conditions/cases with a default fallback.

Q35. How to iterate over a list in JSX? What is the map method? The map() method is a JavaScript function usable in JSX that iterates over an array and returns a new array with each element transformed. It accepts a callback function (which can be an arrow function) that processes each element. Example: numberList.map((number) => number * 2) returns a new array with each number doubled. Definition: the map method allows you to iterate over an array and modify its elements using a callback function.


Q36. Can a browser read a JSX file? No. Browsers cannot directly interpret or understand JSX. Babel converts JSX into equivalent JavaScript code that browsers can understand.


Q37. What is a transpiler? What is the difference between compiler and transpiler? Transpiler: a tool that converts source code from one high-level language (e.g., JSX) to another high-level language (e.g., JavaScript). Example: Babel. Compiler: a tool that converts a high-level language (e.g., Java) to a lower-level language (e.g., machine code). Key difference: compiler = high-to-low level; transpiler = high-to-high level.


Q38. Is it possible to use JSX without React? Yes, technically possible by creating your own transpiler like Babel. However, it is not recommended because JSX is tightly integrated with React and relies on many React-specific features.


CHAPTER 5 — COMPONENTS (FUNCTIONAL & CLASS)

Q39. What are the types of React components? Two types:

  1. Functional components — defined as a JavaScript function, originally stateless but can now manage state using Hooks.
  2. Class components — defined as a JavaScript class, stateful by nature using lifecycle methods and this.state.

Q40. What are functional components? Functional components are the standard way of declaring components using a JavaScript function (regular or arrow function). Two key points:

  1. Defined as JavaScript functions.
  2. Originally stateless but can now manage state using React Hooks.

Q41. How do you pass data between functional components in React? Using props (properties). Props are a way to pass data from a parent component to a child component. The parent passes data as attributes on the child component tag, and the child receives and uses it via its props parameter.


Q42. What is prop drilling in React? Prop drilling is the process of passing the same data (via props) through multiple layers of components — from a top parent component down through intermediate components to a deeply nested child — even when intermediate components do not need the data. It is called "drilling" because you drill down through layers.


Q43. Why should you avoid prop drilling? In how many ways can you avoid it? Why avoid it:

  1. Difficult maintenance — changes in data flow require updates across multiple components.
  2. Increased complexity — reduces code readability.
  3. Debugging challenges — tracking data through multiple layers is hard.

Five ways to avoid prop drilling:

  1. Context API
  2. Redux
  3. Component composition
  4. Callback functions
  5. Custom Hooks

Q44. What are class components in React? Class components are declared using a JavaScript class that extends React's Component class. Key points:

  1. Defined using JavaScript classes (extends Component).
  2. Stateful — can manage local state using this.state.
  3. Have a render() method responsible for returning JSX.
  4. Exported like functional components for use in other files.

Q45. How to pass data between class components in React? Using this.props. In the parent class component, pass data as an attribute on the child component tag. In the child class component, access it via this.props.attributeName. Definition: this.props is used in child class components to access properties/data passed from the parent component.


Q46. What is the role of the 'this' keyword in class components? The 'this' keyword is a reference to the current instance of the class. In class components, it refers to the instance of the component class. It is used to access props (this.props), state (this.state), and other class methods. Without 'this', props and state cannot be related to their class. Short answer: 'this' is used to refer to the instance of the class.


Q47. What are the five differences between functional and class components?

  1. Syntax: functional = JavaScript function; class = JavaScript class.
  2. State: functional originally stateless (now uses Hooks); class uses this.state.
  3. Lifecycle methods: functional components do not have lifecycle methods; class components do.
  4. Readability: functional = more readable, concise, simple; class = more verbose/complex.
  5. 'this' keyword: functional has no 'this'; class uses 'this' for accessing properties. Bonus: functional has no render() method; class requires render() to return JSX.

CHAPTER 6 — ROUTING

Q48. What is routing and router in React? Routing means navigation — React provides a way to navigate from one component to another without refreshing the page. The URL updates and the component changes without a full page reload. Definition: routing allows you to create a SPA with navigation without a full page refresh. React Router is a library for handling routing in React — it enables navigation and rendering of different components based on the URL.


Q49. How to implement routing in React? Steps:

  1. Install react-router-dom using npm.
  2. In App.js, import Routes, Route, and Link from the library.
  3. Use the Link component for navigation items.
  4. Define routes using the Route component with path and element attributes.
  5. In index.js, wrap the App component inside the BrowserRouter component.

Q50. What are the roles of Routes and Route components in React Router? Routes: a container component that holds a collection of Route components — just a wrapper for multiple Routes. Route: defines a path and specifies which component/element to render when the URL matches that path. Example: <Route path='/about' element={<About />} /> renders the About component when the URL is /about.


Q51. What are route parameters in routing? Route parameters are dynamic values passed as part of the URL path. Example: <Route path='/user/:userId' element={<UserProfile />} /> — here userId is a route parameter. Definition: route parameters are a way to pass dynamic data/values to a component as part of the URL path.


Q52. What is the role of the Switch component in React Router? Switch is a container for multiple Route components. When multiple routes have similar or overlapping paths, Switch executes only the first matched route and ignores the rest. It is commonly used to handle 404 / Not Found routes as a default fallback.


Q53. What is the role of the exact prop in routing? By default, a route with path='/about' also matches '/about/team', '/about/contact', etc. Adding the exact prop makes the route match only the exact path '/about' and nothing else. Definition: the exact prop is used with the Route component to match exactly the provided path.


CHAPTER 7 — HOOKS (USESTATE & USEEFFECT)

Q54. What are React Hooks? Which are the top React Hooks? React Hooks are inbuilt functions provided by React that allow functional components to use state and lifecycle features. Before Hooks, class component lifecycle methods were used. Hooks are simpler and designed for functional components. They must be imported from the React library.

Top Hooks: useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useLayoutEffect.


Q55. What is the role of the useState Hook and how does it work? useState is a React Hook for managing state in functional components. Working:

  1. Import useState from React.
  2. Call useState(initialValue) — it returns an array of two elements via array destructuring: [currentStateValue, setterFunction].
  3. The setter function (e.g., setCount) updates the state and triggers a re-render.
  4. useState is called only once when the component first loads; after that, only the setter function is called on updates.

Array destructuring assigns the two array elements to individual variables. The setter function is a React library function returned by useState that maintains the state.


Q56. What is the role of the useEffect Hook, how does it work, and what is its use? useEffect is used to perform side effects in functional components. Side effects are operations (e.g., data fetching from an API, subscriptions) that happen after the component has been initially rendered. useEffect accepts two parameters:

  1. An effect function — contains the side effect code (e.g., fetch data from API).
  2. A dependency array.

The effect function runs after the component renders. Key points:

  1. useEffect is called after the component renders.
  2. It accepts an effect function and a dependency array.

Q57. What is the dependency array in useEffect? The dependency array is the second parameter of useEffect. It contains values (dependencies) that, when changed, cause the effect function to re-run. Example: [userId] as the dependency — when userId changes, the data is re-fetched from the API. It is an array because you may have multiple dependencies.


Q58. What is the meaning of an empty array [] in useEffect? An empty array [] as the second parameter means the effect function runs only once — when the component first mounts. Because there are no dependencies, there is nothing to trigger a re-run. Use this when the side effect only needs to happen once (e.g., fetching fixed data).


CHAPTER 8 — HOOKS (USECONTEXT)

Q59. What is the role of the useContext Hook? useContext provides a way to pass data from a parent component to child components without using props (avoiding prop drilling). How it works:

  1. Create a context object: const MyContext = createContext().
  2. In the parent, wrap child components in MyContext.Provider and set its value prop.
  3. In any child, call useContext(MyContext) — it returns the context value directly.

The alternative is using MyContext.Consumer, but useContext is simpler and preferred.


Q60. What is the createContext method? What are provider and consumer properties?

  1. createContext() returns an object with Provider and Consumer properties.
  2. The Provider property provides the context value to all its child components.
  3. The useContext method or the Consumer property can be used to consume/get the context value in child components.

Q61. When to use the useContext Hook instead of props? Use useContext instead of props when you want to avoid prop drilling and access context values directly within deeply nested components. For one level of parent-child, props are simple and fine. For multiple levels, useContext is better.

Real-world scenarios: theme switching, localization, centralized configuration, user preferences, notification systems.


CHAPTER 9 — COMPONENT LIFECYCLE METHODS

Q62. What are component lifecycle phases? Three lifecycle phases:

  1. Mounting phase — component is created and inserted into the DOM for the first time; methods execute before the component is rendered.
  2. Updating phase — component re-renders when state or props change.
  3. Unmounting phase — component is being removed from the DOM (e.g., replaced by another component).

Q63. What are component lifecycle methods? Each phase has methods that execute in sequence.

Mounting phase (in order): constructor → static getDerivedStateFromProps → render → componentDidMount. Updating phase (in order): static getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate. Unmounting phase: componentWillUnmount.

Definition: component lifecycle methods are special methods that get called at various stages of a component's life.


Q64. What are constructors in class components? When to use them? The Constructor is the first method of the mounting phase. It is a specialized function that is invoked automatically when the component is called — no need to call it explicitly. Use the Constructor for:

  1. Initializing the component state (this.state = { count: 0 }).
  2. Performing mandatory setup before the component renders.

The component will not render until the Constructor code completes.


Q65. What is the role of the super keyword in the constructor? The super keyword calls the Constructor of the parent class (Component from React). Rule: before the child class Constructor runs, the parent class Constructor must run first — super() enforces this. Removing super() will break the application. Conclusion: super calls the parent class Constructor to ensure the parent's initialization logic runs before the child's.


Q66. What is the role of the render method in the component lifecycle? The render method is responsible for displaying (returning) JSX elements in the UI/DOM. It appears in both the mounting phase (first render) and the updating phase (re-renders after state/props change). Without render(), nothing is displayed in the browser. Definition: the render method returns the React elements that will be rendered to the DOM.


Q67. How can state be maintained in a class component? Two-step process:

  1. Set initial state in the Constructor: this.state = { count: 0 }.
  2. Use this.setState() to update the state — it increments the count and triggers a re-render.

this.setState() is the React Library function that updates state. this.state is used to read and render the current value in the DOM.


Q68. What is the role of the componentDidMount method? componentDidMount is the last method of the mounting phase (runs after render). It is used for side effects — operations that run after the component is already rendered to the DOM, such as fetching external API data or setting up subscriptions. Conclusion: componentDidMount is called after the component has been rendered to the DOM and is mostly used for side effects like data fetching.


CHAPTER 10 — CONTROLLED COMPONENTS

Q69. What are controlled components in React? A controlled component is a component whose form elements (input fields, checkboxes, etc.) are controlled by the application's state. Example: an input field whose value is stored in state and updates via an onChange event — every keystroke updates the state and the state drives the input value.


Q70. What are the differences between controlled and uncontrolled components? Controlled:

  1. Uses application state to save changes.
  2. State is updated on every event.
  3. Recommended best practice for forms.

Uncontrolled:

  1. No state management — values accessed directly via useRef.
  2. Less re-rendering.
  3. Useful when integrating with non-React libraries.
  4. Less commonly considered a best practice.

Q71. What are the characteristics of a controlled component?

  1. State control — form element value is stored in component state.
  2. Event handling — changes trigger an event (e.g., onChange).
  3. State update — the event handler updates the state with the new value.
  4. Rendering — component re-renders with the updated state, and the form element reflects the new value.

Q72. What are the advantages of using controlled components in React forms?

  1. Single source of truth — state is the single source that provides values to all form elements; it cannot be directly manipulated.
  2. Predictable and synchronized updates — easier to implement form validation, dynamic rendering, and lifecycle integration.
  3. Better control and maintainability compared to uncontrolled components.

Q73. How to handle forms in React? The preferred and recommended approach for handling forms in React is by using controlled components.


Q74. How can you handle multiple input fields in a controlled form? Maintain separate state variables for each input field and update them individually using the onChange event handler.


Q75. How do you handle form validation in a controlled component? By using conditional rendering based on the state — validate the input values before updating the state. If the value meets the condition, update the state; otherwise, do not.


Q76. In what scenarios might using uncontrolled components be advantageous? Uncontrolled components can be beneficial when:

  1. Integrating with non-React libraries.
  2. Dealing with forms where controlled components are not possible.

CHAPTER 11 — CODE SPLITTING

Q77. What is code splitting in React? Without code splitting: all files are bundled together and sent to the browser in one single request. With code splitting: each file/chunk is loaded on demand — CSS only when needed, JS only when needed, etc. Definition: code splitting is a technique to split the JavaScript bundle into smaller chunks which are loaded on demand.


Q78. How to implement code splitting in React? Three steps:

  1. Use React.lazy() to lazily import components: const CodeSplit = React.lazy(() => import('./CodeSplit')).
  2. Wrap components with Suspense to handle loading: <Suspense fallback={<div>Loading...</div>}><CodeSplit /></Suspense>.
  3. Install and configure webpack for dynamic imports.

lazy() loads the component only when it is actually needed. Until then, Suspense shows the fallback UI.


Q79. What is the role of lazy and Suspense in React? React.lazy: a function that allows you to load a component lazily — it enables code splitting by importing a component asynchronously, only when needed. Suspense: a component that displays a fallback UI while the lazily loaded component is being fetched. Once loaded, the component replaces the fallback UI.


Q80. What are the pros and cons of code splitting? Pros:

  1. Faster initial load time — only loads necessary code.
  2. Optimized bandwidth usage — less data transferred.
  3. Improved caching — smaller focused chunks are easier to cache.
  4. Parallel loading — multiple chunks can load simultaneously.
  5. Easier maintenance — more modular and independent code.

Cons:

  1. Increased project complexity.
  2. Tooling dependency (webpack, Babel configuration).
  3. Potential runtime errors.
  4. Increased number of HTTP requests.
  5. Learning curve for new developers.

Q81. What is the role of the import() function in code splitting? The import() function returns a promise that allows dynamic loading of modules.


Q82. What is the purpose of the fallback property in Suspense? The fallback property provides a loading indicator or UI while the dynamically imported component is being loaded.


Q83. Can you dynamically load CSS files using code splitting in React? Yes. Using dynamic import for CSS files allows you to load styles on demand along with the corresponding components.


Q84. How do you inspect and analyze the generated chunks in a React application? Use tools like Webpack Bundle Analyzer to analyze the size and composition of the generated chunks.


CHAPTER 12 — ADVANCED / MISCELLANEOUS

Q85. What is a Higher Order Component (HOC) in React? A Higher Order Component is a component that takes another component as an argument and adds extra features/functionality to it. Example: HOCLogger(HocUser) — HOCLogger adds logging functionality. When HocUser is exported through HOCLogger, the HOC's extra features run first, then the main component runs. Real-world use: error logging. HOCs are reusable across multiple components.


Q86. What are the five ways to style React components?

  1. Inline styles — style attribute directly on the element as a JS object.
  2. CSS style sheets — separate .css files imported into components.
  3. CSS modules — scoped .module.css files to avoid global style conflicts.
  4. Global style sheets — a single global CSS file.
  5. CSS Frameworks — like Bootstrap, Tailwind, etc.

Q87. What are the differences between React and React Native?

  1. React is a library; React Native is a framework.
  2. React builds web interfaces; React Native builds mobile apps.
  3. React runs on web browsers; React Native runs on iOS and Android.
  4. React uses HTML and CSS for UI; React Native uses native UI components (View, Text, etc.).
  5. React is deployed as a web app; React Native is deployed through the App Store or Google Play.

Q88. What is GraphQL? GraphQL is a query language for APIs and a runtime for executing those queries with your existing data. Developed by Facebook. React components can use GraphQL queries to fetch data required for rendering. React and GraphQL are often used together because both are developed by Facebook and are compatible with each other.


Q89. What are the top three ways to achieve state management in React? When to use what?

  1. useState Hook — use for simple, single-component level state. Best for small components with isolated state. It is lightweight and built into React.
  2. Context API — use to avoid prop drilling for sharing global data across multiple components. Good for small to medium-sized applications.
  3. Redux — use for large-scale applications with complex state. It has a centralized store and actions providing a predictable state management pattern, ideal for scalability.

Q90. How can you implement authentication in a React application? Using JWT (JSON Web Token) authentication — 8 steps:

  1. User enters username/password in browser.
  2. Credentials sent to API via POST request.
  3. API validates credentials.
  4. If valid, API creates a JWT token and sends it back to the client.
  5. Client stores JWT in browser's local storage.
  6. For subsequent requests, JWT is sent in the request header.
  7. API validates the token signature.
  8. If valid, API sends data; client displays it.

The user only logs in once — after that, the token handles all subsequent authentication.


Q91. What is the use of React Profiler? React Profiler is a set of tools that allows developers to profile/analyze the performance of a React application. Wrap the code to be measured inside a Profiler component with an id and an onRender callback. The onRender function logs start time, execution time, and end time of the code execution, helping identify performance bottlenecks.


Q92. What is the difference between Fetch and Axios for API calls in React?

  1. Fetch is a built-in JavaScript function requiring no extra libraries; Axios is a third-party library requiring installation and import.
  2. Fetch returns a Promise; Axios also uses Promises but additionally supports interceptors — useful for adding tokens, logging, and error handling across multiple requests.

When to use: if HTTP requests are simple, use Fetch. If you need advanced control over interceptors for multiple requests/responses, use Axios.


Q93. What are the popular testing libraries for React? Four most popular testing libraries:

  1. Jest
  2. React Testing Library
  3. Enzyme
  4. Cypress

Q94. How can you optimize performance in a React application?

  1. Memoization — use useMemo and useCallback to avoid unnecessary recalculations.
  2. Optimize renders — use React.Fragment to avoid unnecessary wrapper DOM nodes.
  3. Lazy loading — use React.lazy() to reduce initial bundle size.
  4. Code splitting — divide the app into smaller chunks loaded on demand.
  5. Optimize images and assets — compress images, use responsive images, and lazy load images to reduce bandwidth.

Q95. Explain reactive programming with an example. Reactive programming is a programming approach that focuses on reacting to changes and events in a declarative and asynchronous manner. Example: Google's autocomplete — as you type, Google continuously captures keyboard events and fetches/displays suggestions without blocking the UI. Declarative means writing code for what you want to achieve (not step-by-step). Asynchronous means fetching happens without blocking user input.


Q96. In how many ways can we implement reactive programming in React? Ways to handle reactive programming in React:

  1. State and Props
  2. React Hooks
  3. Event handling
  4. Context API
  5. Redux
  6. Component lifecycle methods
  7. async/await
  8. RxJS and Observables

If you are using event handling with state management techniques like Hooks or Redux, you are likely already doing reactive programming in your project.


Q97. How to pass data from a child component to a parent component in React? Using callback functions:

  1. Define a callback function in the parent that accepts data as an argument.
  2. Pass the callback function as a prop to the child component.
  3. In the child, define a function (e.g., dataToParent) that calls the received callback with the data (e.g., input field value).
  4. When triggered (e.g., button click), the callback executes in the parent context and receives the data.

Definition: the parent provides a callback function to the child, and the child invokes this callback to pass data back to the parent.


That covers all the questions and answers from the transcript across all chapters.

Share:

0 comments:

Post a Comment