{"id":939,"date":"2026-10-12T09:00:00","date_gmt":"2026-10-12T03:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/"},"modified":"2026-10-25T00:21:08","modified_gmt":"2026-10-24T18:51:08","slug":"react-js-interview-questions","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/","title":{"rendered":"React JS Interview Questions: 110 Most Asked, with Full Answers"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">React JS interview questions show up in almost every frontend and full-stack interview, because React is still the most used library for building web user interfaces. This post gives you 110 of the most asked questions, grouped from basic to advanced, and every one of them now has a full answer in simple English, with code examples you can try.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Full-stack rounds often ask how the frontend talks to the backend, so the <a href=\"https:\/\/smitabharat.com\/blog\/go-rest-api-tutorial\/\">Go REST API tutorial<\/a> and the <a href=\"https:\/\/smitabharat.com\/blog\/go-rest-api-interview-questions-part-19\/\">Go REST API interview questions<\/a> are good companions. For a short warm-up, also read our earlier <a href=\"https:\/\/smitabharat.com\/blog\/react-questions\/\">React questions<\/a> post. The answers here match React 19 and current best practice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Do React JS Interview Questions Cover?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">React is a JavaScript library for building user interfaces from small, reusable pieces called components. You describe what the screen should look like for the current data, and React updates the page when that data changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of LEGO bricks. Each brick is a small component, such as a button or a card. You snap bricks together into bigger parts, such as a product list, and then into a full page. If one brick changes colour, you only swap that brick, not the whole model.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Most React JS interview questions test six areas: JSX and components, props and state, hooks, rendering and performance, routing and data, and testing. Senior rounds add React 19 features, architecture and real debugging scenarios.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to Use These React JS Interview Questions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Do not try to learn 110 answers by heart. Instead, use the list in three passes.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, read each question and try to answer it in two or three sentences before you read the answer.<\/li>\n\n\n<li>Next, practise those out loud, with a small example you have built.<\/li>\n\n\n<li>Finally, type the components from the hands-on section into a new Vite project and run them.<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The table below shows how interview rounds usually use these questions.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Round<\/th><th>Focus<\/th><th>Question range<\/th><\/tr><\/thead><tbody><tr><td>Phone screen<\/td><td>JSX, components, props, state<\/td><td>Q1 to Q40<\/td><\/tr><tr><td>Technical round<\/td><td>Hooks, rendering, forms, routing<\/td><td>Q41 to Q90<\/td><\/tr><tr><td>Senior round<\/td><td>React 19, testing, scenarios<\/td><td>Q91 to Q110<\/td><\/tr><tr><td>Live coding<\/td><td>Build a small component<\/td><td>Hands-on section<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">How React Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">React follows the same cycle every time data changes. Something updates state, React calls your component again, compares the new result with the old one, and changes only the parts of the real page that differ.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-1-1024x640.png\" alt=\"React JS interview questions diagram showing state change, render, reconciliation, commit and effects\" class=\"wp-image-937\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">A state change re-runs the component, React compares the result with the last render, updates only the changed DOM nodes, then runs effects.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">This comparison step is called reconciliation. React builds a light copy of the UI in memory (often called the virtual DOM), finds the difference, and then updates the browser DOM in one batch. After that, your effects run, for example to fetch data or start a timer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Basic React JS Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These React JS interview questions check that you know the core ideas and terms. Freshers should be able to answer all of them, so type the small examples into a test project as you read.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What is React, and why is it so popular?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React is an open-source JavaScript library for building user interfaces, made by Meta (Facebook) and released in 2013. You build the screen from small, reusable pieces called components, and React updates the page efficiently when your data changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is popular for several reasons.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Components:<\/strong> you build once and reuse everywhere, such as a <code>Button<\/code> or <code>ProductCard<\/code>.<\/li>\n\n\n<li><strong>Declarative style:<\/strong> you describe what the UI should look like, and React handles the DOM updates.<\/li>\n\n\n<li><strong>Huge ecosystem:<\/strong> routers, state libraries, UI kits and frameworks like Next.js.<\/li>\n\n\n<li><strong>Strong job market and community:<\/strong> lots of tutorials, tools and developers.<\/li>\n\n\n<li><strong>React Native:<\/strong> the same ideas work for mobile apps.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. Is React a library or a framework?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React itself is a library. It focuses on one job: building the UI. It does not decide how you handle routing, data fetching, forms or project structure, so you pick other tools for those.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That is why frameworks are built on top of React, such as Next.js and React Router in framework mode. They add routing, server rendering, data loading and build setup. So you can say &#8220;React is a UI library, and React frameworks turn it into a full solution&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. What is a single-page application (SPA)?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A single-page application loads one HTML page once, then updates the content with JavaScript as the user moves around, without full page reloads. When you click a link, the app changes the URL and shows a new view, and only data is fetched from the server.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SPAs feel fast and smooth, like a mobile app. The downsides are a larger first JavaScript download and weaker SEO if nothing is rendered on the server. Modern React frameworks fix this with server rendering, while keeping the SPA feel after the first load.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. What is JSX?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">JSX is a syntax extension for JavaScript that lets you write HTML-like code inside JavaScript. It makes UI code easy to read, because the markup and the logic for a component sit together.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Greeting({ name }) {\n  const hour = new Date().getHours();\n  return (\n    &lt;h1 className=\"title\"&gt;\n      {hour &lt; 12 ? \"Good morning\" : \"Hello\"}, {name}!\n    &lt;\/h1&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Anything inside curly braces <code>{}<\/code> is a JavaScript expression. JSX is not HTML, so attributes use camelCase names like <code>className<\/code>, <code>onClick<\/code> and <code>htmlFor<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. Why does JSX need to be compiled, and what does it turn into?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Browsers do not understand JSX, so a build tool such as Vite (using esbuild or SWC) or Babel turns it into normal JavaScript before it runs. Each JSX tag becomes a function call that creates a React element, which is a plain object describing what to show.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ You write:\nconst el = &lt;button className=\"buy\"&gt;Buy now&lt;\/button&gt;;\n\n\/\/ It becomes roughly (modern automatic JSX runtime):\nimport { jsx } from \"react\/jsx-runtime\";\nconst el = jsx(\"button\", { className: \"buy\", children: \"Buy now\" });<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Older setups used <code>React.createElement<\/code>, which is why old files always had <code>import React from \"react\"<\/code>. With the newer JSX runtime, that import is not needed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. What is the virtual DOM?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The virtual DOM is a lightweight copy of the UI kept in memory as plain JavaScript objects. When state changes, React creates a new virtual tree, compares it with the previous one, works out the smallest set of changes, and then updates the real browser DOM.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of editing a document by first writing your changes on a draft, then copying only the changed lines to the final copy. Updating the real DOM is slow compared with working with JavaScript objects, so this keeps updates efficient and lets you write simple code that &#8220;re-renders everything&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. How is the virtual DOM different from the real DOM?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The real DOM is the browser&#8217;s actual page structure that users see. The virtual DOM is React&#8217;s in-memory description of that page.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Real DOM<\/th><th>Virtual DOM<\/th><\/tr><\/thead><tbody><tr><td>What it is<\/td><td>Browser objects that draw the page<\/td><td>Plain JavaScript objects<\/td><\/tr><tr><td>Speed to change<\/td><td>Slower, can cause layout and repaint<\/td><td>Fast, just objects in memory<\/td><\/tr><tr><td>Who updates it<\/td><td>Browser APIs<\/td><td>React, during render<\/td><\/tr><tr><td>Shown to users<\/td><td>Yes<\/td><td>No<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So React changes the virtual DOM freely and touches the real DOM only where something really changed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. What is reconciliation?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reconciliation is the process React uses to compare the new virtual tree with the previous one and decide what to change in the real DOM. React uses a fast comparison based on two simple rules.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If an element&#8217;s type changes, such as a <code>div<\/code> becoming a <code>section<\/code>, React throws away the old part and builds a new one.<\/li>\n\n\n<li>In lists, React uses <code>key<\/code> to match old and new items, so it can move, add or remove the right ones.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">After reconciliation, the commit phase applies the changes to the real DOM, and then effects run.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. What is a component?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A component is a reusable piece of UI, written as a JavaScript function that returns JSX. It can take inputs (props), keep its own data (state) and contain other components. Components are like custom HTML tags you invent for your app.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function ProductCard({ name, price }) {\n  return (\n    &lt;div className=\"card\"&gt;\n      &lt;h3&gt;{name}&lt;\/h3&gt;\n      &lt;p&gt;\u20b9{price}&lt;\/p&gt;\n    &lt;\/div&gt;\n  );\n}\n\n\/\/ Use it like a tag\n&lt;ProductCard name=\"Notebook\" price={120} \/&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. What is the difference between function components and class components?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Function components are plain functions that return JSX and use hooks for state and side effects. Class components extend <code>React.Component<\/code>, keep state in <code>this.state<\/code> and use lifecycle methods like <code>componentDidMount<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Function component<\/th><th>Class component<\/th><\/tr><\/thead><tbody><tr><td>Syntax<\/td><td>A function<\/td><td>A class with <code>render()<\/code><\/td><\/tr><tr><td>State<\/td><td><code>useState<\/code>, <code>useReducer<\/code><\/td><td><code>this.state<\/code>, <code>this.setState<\/code><\/td><\/tr><tr><td>Side effects<\/td><td><code>useEffect<\/code><\/td><td>Lifecycle methods<\/td><\/tr><tr><td>Code size<\/td><td>Shorter<\/td><td>Longer, uses <code>this<\/code><\/td><\/tr><tr><td>New features<\/td><td>All new React features<\/td><td>Few new features<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Both still work, but new code uses function components. The one thing that still needs a class is an error boundary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11. Why do most teams use function components today?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Function components with hooks are shorter, easier to read and easier to test. You do not need to deal with <code>this<\/code> binding, and related logic stays together instead of being split across lifecycle methods.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hooks also make it easy to share logic with custom hooks, which replaced older patterns like higher-order components and render props in most cases. All new React features, such as <code>use<\/code>, Server Components and Actions, are built for function components.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12. Why must a component name start with a capital letter?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">JSX uses the first letter to decide what a tag is. A lowercase tag, such as <code>&lt;div&gt;<\/code> or <code>&lt;button&gt;<\/code>, is treated as a built-in HTML element. A capitalised tag, such as <code>&lt;ProductCard&gt;<\/code>, is treated as a component you defined.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So if you name a component <code>productCard<\/code>, React tries to create an HTML element called <code>productcard<\/code>, which does nothing. Always use PascalCase for component names.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q13. What is a React Fragment, and why use one?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A component must return one parent element. A Fragment lets you group several elements without adding an extra <code>div<\/code> to the page. You write it as <code>&lt;&gt;...&lt;\/&gt;<\/code> or <code>&lt;Fragment&gt;...&lt;\/Fragment&gt;<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function TableRow({ name, price }) {\n  return (\n    &lt;&gt;\n      &lt;td&gt;{name}&lt;\/td&gt;\n      &lt;td&gt;{price}&lt;\/td&gt;\n    &lt;\/&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This keeps the HTML clean and valid, for example inside tables where an extra <code>div<\/code> would break the layout. Use the long form <code>&lt;Fragment key={id}&gt;<\/code> when a fragment in a list needs a key.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q14. How do you render a list in React?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use JavaScript&#8217;s <code>map()<\/code> to turn an array of data into an array of JSX elements, and give each item a unique <code>key<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function ProductList({ products }) {\n  return (\n    &lt;ul&gt;\n      {products.map((product) =&gt; (\n        &lt;li key={product.id}&gt;\n          {product.name}: \u20b9{product.price}\n        &lt;\/li&gt;\n      ))}\n    &lt;\/ul&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also <code>filter()<\/code> before mapping, for example to show only products in stock.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q15. Why does each item in a list need a key?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key tells React which item is which between renders. When the list changes, for example an item is added, removed or moved, React uses keys to match old and new items. So it can keep each item&#8217;s state and DOM node with the right data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Without stable keys, React may reuse the wrong DOM node for an item, which causes bugs such as an input showing the text of another row. Keys must be unique among siblings and stay the same for the same item, so database IDs are ideal.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q16. Why is using the array index as a key often a bad idea?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The index changes when items are added, removed or reordered. If you delete the first item, every other item gets a new index, so React thinks the items themselves changed. It may then keep state, such as typed text or a checkbox, attached to the wrong row.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Using the index is only safe when the list never changes order, never has items inserted or removed in the middle, and items have no state. Otherwise, use a stable ID from your data, or create one when the item is created, such as <code>crypto.randomUUID()<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q17. How do you show something only when a condition is true?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are a few common patterns for conditional rendering.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Cart({ items, isLoggedIn }) {\n  if (!isLoggedIn) {\n    return &lt;p&gt;Please log in.&lt;\/p&gt;;          \/\/ early return\n  }\n  return (\n    &lt;div&gt;\n      {items.length &gt; 0 &amp;&amp; &lt;CartList items={items} \/&gt;}   {\/* &amp;&amp; *\/}\n      {items.length === 0 ? &lt;p&gt;Cart is empty&lt;\/p&gt; : &lt;CheckoutButton \/&gt;} {\/* ternary *\/}\n    &lt;\/div&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Be careful with <code>&amp;&amp;<\/code> and numbers. <code>{count &amp;&amp; &lt;Badge \/&gt;}<\/code> shows <code>0<\/code> on the page when <code>count<\/code> is 0, so write <code>{count &gt; 0 &amp;&amp; &lt;Badge \/&gt;}<\/code> instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q18. How do you add a CSS class in JSX, and why is it className?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In JSX, you use <code>className<\/code> instead of <code>class<\/code>, because <code>class<\/code> is a reserved word in JavaScript and JSX maps to DOM properties, where the property is also <code>className<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;button className={isActive ? \"tab active\" : \"tab\"}&gt;Orders&lt;\/button&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use inline styles with an object, such as <code>style={{ color: \"red\", fontSize: 14 }}<\/code>, CSS Modules, utility classes like Tailwind CSS, or CSS-in-JS libraries. Small helpers like <code>clsx<\/code> make joining classes easier.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q19. How do you start a new React project today, now that Create React App is deprecated?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create React App was officially deprecated in early 2025, so new projects should not use it. The React team now recommends two paths.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Use a framework<\/strong> for most apps: Next.js, React Router (framework mode) or Expo for mobile. You get routing, data loading and server rendering built in.<\/li>\n\n\n<li><strong>Use a build tool<\/strong> for a simple SPA or to learn: Vite is the most popular choice.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>npm create vite@latest my-app -- --template react-ts\ncd my-app\nnpm install\nnpm run dev<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q20. What are frameworks such as Next.js and React Router, and when do you need one?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React frameworks add the parts React itself leaves out, so you do not have to build them yourself.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Next.js:<\/strong> file-based routing, Server Components, server rendering, static generation, API routes and image optimisation.<\/li>\n\n\n<li><strong>React Router (framework mode, formerly Remix):<\/strong> nested routes with data loading and form actions, server rendering, and it also works as a simple client-side router.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You need a framework when your app needs SEO, fast first loads, server rendering or many pages with data loading. For an internal dashboard behind a login, a Vite SPA with React Router as a library can be enough.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Props and State React JS Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Props and state are the heart of React. So almost every round starts with these React JS interview questions, and many &#8220;what does this print?&#8221; questions come from here.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q21. What are props?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Props (short for properties) are the inputs a parent passes to a child component, like arguments to a function. They let you reuse one component with different data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Avatar({ name, size = 40 }) {\n  return &lt;img src={`\/avatars\/${name}.png`} alt={name} width={size} \/&gt;;\n}\n\nfunction Profile() {\n  return &lt;Avatar name=\"asha\" size={80} \/&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Props can be any JavaScript value: strings, numbers, objects, arrays, functions and even JSX. Inside the component, you usually destructure them in the parameter list.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q22. Can a child component change its props?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Props are read-only. A component must never change the props it receives, because they belong to the parent. React components should act like pure functions with respect to their props: the same props should give the same output.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a child needs to change something, the parent passes down a function as a prop, such as <code>onChange<\/code>, and the child calls it. Then the parent updates its own state and passes new props down.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q23. What is the children prop?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>children<\/code> is a special prop that holds whatever you put between a component&#8217;s opening and closing tags. It lets you build wrapper components, such as cards, modals and layouts, that do not know their content in advance.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Card({ title, children }) {\n  return (\n    &lt;div className=\"card\"&gt;\n      &lt;h2&gt;{title}&lt;\/h2&gt;\n      &lt;div className=\"card-body\"&gt;{children}&lt;\/div&gt;\n    &lt;\/div&gt;\n  );\n}\n\n&lt;Card title=\"Order summary\"&gt;\n  &lt;p&gt;3 items&lt;\/p&gt;\n  &lt;p&gt;Total: \u20b91,250&lt;\/p&gt;\n&lt;\/Card&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q24. How do you set a default value for a prop?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In function components, use JavaScript default values when you destructure the props.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Button({ label = \"Submit\", variant = \"primary\", onClick }) {\n  return &lt;button className={`btn btn-${variant}`} onClick={onClick}&gt;{label}&lt;\/button&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The default is used when the prop is missing or <code>undefined<\/code>, but not when it is <code>null<\/code>. The old <code>defaultProps<\/code> property is no longer supported for function components in React 19, so use default parameters instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q25. What is prop drilling, and how do you avoid it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Prop drilling means passing a prop through many layers of components that do not use it, just so a deep child can get it. For example, passing <code>user<\/code> from <code>App<\/code> to <code>Layout<\/code> to <code>Sidebar<\/code> to <code>Menu<\/code> to <code>UserBadge<\/code>. It makes code noisy and hard to change.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can avoid it in a few ways.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Composition:<\/strong> pass components as <code>children<\/code> or props, so the parent renders the deep child directly.<\/li>\n\n\n<li><strong>Context:<\/strong> put shared data such as the theme or current user in a Context, and read it with <code>useContext<\/code> where needed.<\/li>\n\n\n<li><strong>State libraries:<\/strong> use Zustand, Redux Toolkit or similar for app-wide state.<\/li>\n\n\n<li><strong>Server state tools:<\/strong> use TanStack Query for data from the server, so any component can read it.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q26. What is state?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">State is data that a component owns and that can change over time, such as a counter, the text in an input, or whether a menu is open. When state changes, React re-renders the component to show the new value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useState } from \"react\";\n\nfunction LikeButton() {\n  const [likes, setLikes] = useState(0);\n  return &lt;button onClick={() =&gt; setLikes(likes + 1)}&gt;\u2764 {likes}&lt;\/button&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each component instance has its own state. Two <code>LikeButton<\/code>s on the page keep separate counts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q27. What is the difference between props and state?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Props come from the parent and are read-only. State lives inside the component and changes over time with its setter. The table below sums up the main differences.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Props<\/th><th>State<\/th><\/tr><\/thead><tbody><tr><td>Who owns it<\/td><td>The parent component<\/td><td>The component itself<\/td><\/tr><tr><td>Can it change inside the component<\/td><td>No, read-only<\/td><td>Yes, with the setter<\/td><\/tr><tr><td>Direction<\/td><td>Flows down to children<\/td><td>Local, can be passed down as props<\/td><\/tr><tr><td>Causes a re-render<\/td><td>When the parent passes new props<\/td><td>When you call the setter<\/td><\/tr><tr><td>Example<\/td><td>A product name passed to a card<\/td><td>A counter or form input value<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-2-1024x640.png\" alt=\"React JS interview questions comparison of props and state\" class=\"wp-image-938\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Props flow down from the parent and are read-only, while state lives inside a component and changes over time.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So use props to configure a component from outside. Use state for data that the component itself changes over time. One component&#8217;s state often becomes another component&#8217;s props.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q28. Why should you never change state directly?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React only re-renders when you call the state setter with a new value. If you change state directly, such as <code>user.name = \"Ravi\"<\/code> or <code>items.push(item)<\/code>, React does not know anything changed, so the screen does not update. It can also break features that compare old and new values, such as <code>React.memo<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So always create a new value and pass it to the setter: <code>setUser({ ...user, name: \"Ravi\" })<\/code> or <code>setItems([...items, item])<\/code>. Treat state as read-only, just like props.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q29. Why is a state update not visible right away in the same function?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Calling a setter does not change the state variable in the current render. It asks React to re-render with the new value. Inside the current function call, the variable still holds the old value, like a snapshot.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Counter() {\n  const [count, setCount] = useState(0);\n\n  function handleClick() {\n    setCount(count + 1);\n    console.log(count); \/\/ still 0 here, the new value shows in the next render\n  }\n  return &lt;button onClick={handleClick}&gt;{count}&lt;\/button&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you need the new value right away, calculate it in a variable first, such as <code>const next = count + 1; setCount(next);<\/code>, and use <code>next<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q30. What is the updater function form, such as setCount(c =&gt; c + 1)?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of a new value, you can pass a function to the setter. React calls it with the latest pending state and uses its return value. This matters when the new state depends on the old one, especially with several updates in a row.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function addThree() {\n  setCount(count + 1); \/\/ uses the snapshot value\n  setCount(count + 1); \/\/ same snapshot\n  setCount(count + 1); \/\/ result: count + 1 only\n}\n\nfunction addThreeCorrect() {\n  setCount((c) =&gt; c + 1);\n  setCount((c) =&gt; c + 1);\n  setCount((c) =&gt; c + 1); \/\/ result: count + 3\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So use the updater form whenever the next state is based on the previous state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q31. What is lifting state up?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Lifting state up means moving shared state to the closest common parent of the components that need it. The parent then passes the state down as props, plus functions to change it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a <code>SearchBox<\/code> and a <code>ProductList<\/code> both need the search text. If each kept its own copy, they would get out of sync. So you keep <code>query<\/code> in their parent <code>ProductPage<\/code>, pass <code>query<\/code> and <code>onQueryChange<\/code> to <code>SearchBox<\/code>, and pass <code>query<\/code> to <code>ProductList<\/code>. This keeps one source of truth.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q32. What is a controlled component?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A controlled component is a form input whose value comes from React state. The input shows the state value, and every change goes through an <code>onChange<\/code> handler that updates the state.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function EmailInput() {\n  const [email, setEmail] = useState(\"\");\n  return (\n    &lt;input\n      type=\"email\"\n      value={email}\n      onChange={(e) =&gt; setEmail(e.target.value)}\n    \/&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So React is the single source of truth, which makes it easy to validate as the user types, format input, or disable a button until the form is valid.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q33. What is an uncontrolled component?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An uncontrolled component keeps its own value inside the DOM, like normal HTML. You set a starting value with <code>defaultValue<\/code>, and read the value when needed, for example with a ref or from the form data on submit.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function NewsletterForm() {\n  function handleSubmit(e) {\n    e.preventDefault();\n    const data = new FormData(e.currentTarget);\n    console.log(data.get(\"email\"));\n  }\n  return (\n    &lt;form onSubmit={handleSubmit}&gt;\n      &lt;input name=\"email\" type=\"email\" defaultValue=\"\" \/&gt;\n      &lt;button&gt;Subscribe&lt;\/button&gt;\n    &lt;\/form&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It means less code and fewer re-renders, and it fits well with React 19 form Actions. File inputs are always uncontrolled.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q34. How do you handle events such as onClick and onChange?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You pass a function to an event prop written in camelCase, such as <code>onClick<\/code>, <code>onChange<\/code> or <code>onSubmit<\/code>. Pass the function itself, do not call it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function SaveButton() {\n  function handleClick(event) {\n    console.log(\"Saved!\", event.type);\n  }\n  return &lt;button onClick={handleClick}&gt;Save&lt;\/button&gt;; \/\/ not handleClick()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Writing <code>onClick={handleClick()}<\/code> is a common mistake. It calls the function during render instead of on click. To stop a form from reloading the page, call <code>event.preventDefault()<\/code> in <code>onSubmit<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q35. What is a synthetic event?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A synthetic event is React&#8217;s wrapper around the browser&#8217;s native event. It has the same interface on every browser, such as <code>e.target<\/code>, <code>e.preventDefault()<\/code> and <code>e.stopPropagation()<\/code>, so your code behaves the same everywhere.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React attaches event listeners at the root of your app and sends events to your handlers (event delegation). If you need the original browser event, use <code>e.nativeEvent<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q36. How do you pass an argument to an event handler?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Wrap the call in an arrow function, so it runs only when the event happens.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function TodoList({ todos, onDelete }) {\n  return (\n    &lt;ul&gt;\n      {todos.map((todo) =&gt; (\n        &lt;li key={todo.id}&gt;\n          {todo.text}\n          &lt;button onClick={() =&gt; onDelete(todo.id)}&gt;Delete&lt;\/button&gt;\n        &lt;\/li&gt;\n      ))}\n    &lt;\/ul&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use the event as well: <code>onClick={(e) =&gt; onDelete(todo.id, e)}<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q37. What is one-way data flow?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One-way data flow means data moves in one direction, from parent to child through props. A child cannot change the parent&#8217;s data directly. Instead, it tells the parent about events by calling a function prop, and the parent decides how to update its state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes apps predictable and easy to debug. When something looks wrong, you follow the data up the tree to find which component owns it and changed it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q38. How do a parent and child talk to each other in both directions?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Parent to child is simple: pass props. Child to parent works by the parent passing a callback function as a prop, which the child calls with any data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Parent() {\n  const [rating, setRating] = useState(0);\n  return (\n    &lt;&gt;\n      &lt;StarRating value={rating} onRate={setRating} \/&gt;\n      &lt;p&gt;You rated: {rating}&lt;\/p&gt;\n    &lt;\/&gt;\n  );\n}\n\nfunction StarRating({ value, onRate }) {\n  return [1, 2, 3, 4, 5].map((n) =&gt; (\n    &lt;button key={n} onClick={() =&gt; onRate(n)}&gt;\n      {n &lt;= value ? \"\u2605\" : \"\u2606\"}\n    &lt;\/button&gt;\n  ));\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For siblings, lift the state to their common parent. In rare cases, a parent can call a child&#8217;s function with a ref and <code>useImperativeHandle<\/code>, such as to focus an input.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q39. What is derived state, and why should you avoid storing it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Derived state is a value you can calculate from existing props or state, such as a full name from first and last name, or a filtered list from a list and a search term. Storing it in its own state means you must keep it in sync by hand, which often causes bugs where one updates and the other does not.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Avoid: extra state plus an effect to sync it\nconst [visible, setVisible] = useState([]);\nuseEffect(() =&gt; setVisible(items.filter((i) =&gt; i.name.includes(query))), [items, query]);\n\n\/\/ Better: calculate during render\nconst visible = items.filter((i) =&gt; i.name.includes(query));<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the calculation is expensive, wrap it in <code>useMemo<\/code>, or let the React Compiler handle it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q40. How do you update an object or array in state the right way?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create a new object or array instead of changing the old one. Use spread syntax and array methods that return new arrays.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Object: change one field\nsetUser((u) =&gt; ({ ...u, city: \"Pune\" }));\n\n\/\/ Nested object\nsetUser((u) =&gt; ({ ...u, address: { ...u.address, pin: \"411001\" } }));\n\n\/\/ Array: add, remove, update\nsetTodos((t) =&gt; [...t, newTodo]);\nsetTodos((t) =&gt; t.filter((todo) =&gt; todo.id !== id));\nsetTodos((t) =&gt; t.map((todo) =&gt; (todo.id === id ? { ...todo, done: true } : todo)));<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid methods that change arrays in place, such as <code>push<\/code>, <code>splice<\/code> and <code>sort<\/code>. Use <code>toSorted()<\/code> or copy first. For deeply nested state, a helper library like Immer lets you write simpler update code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Hooks React JS Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Hooks come up in every technical round. These React JS interview questions cover the built-in hooks, their rules and the newer hooks from React 19.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q41. What are hooks, and why were they added?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hooks are special functions whose names start with <code>use<\/code>, such as <code>useState<\/code> and <code>useEffect<\/code>. They let function components use React features like state, side effects, context and refs. They were added in React 16.8 (2019).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Before hooks, you needed class components for state and lifecycle methods, and sharing logic needed awkward patterns like higher-order components and render props. Hooks made components shorter, kept related logic together, and made it easy to share logic with custom hooks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q42. What are the rules of hooks?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are two main rules.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Only call hooks at the top level<\/strong> of a component or custom hook. Never call them inside loops, conditions, nested functions or after an early <code>return<\/code>.<\/li>\n\n\n<li><strong>Only call hooks from React functions,<\/strong> meaning function components or custom hooks, not from normal JavaScript functions.<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">React keeps track of hooks by the order they are called in each render. If a hook is skipped in one render because of an <code>if<\/code>, the order changes and state gets mixed up. The <code>eslint-plugin-react-hooks<\/code> linter checks these rules for you. The newer <code>use<\/code> API is the one exception that can be called inside conditions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q43. What does useState do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useState<\/code> adds a piece of state to a function component. It returns an array with two items: the current value and a setter function. You give it the starting value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const [name, setName] = useState(\"\");\nconst [cart, setCart] = useState([]);\nconst [total, setTotal] = useState(() =&gt; calculateInitialTotal()); \/\/ lazy initial value<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Calling the setter with a new value schedules a re-render with that value. If the starting value is expensive to compute, pass a function, so it runs only on the first render.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q44. What does useEffect do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useEffect<\/code> lets you run side effects after React has updated the screen. Side effects are things outside rendering, such as fetching data, setting up a subscription, starting a timer or changing the page title.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>useEffect(() =&gt; {\n  document.title = `${count} items in cart`;\n}, [count]);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The React team describes effects as a way to &#8220;synchronise with an external system&#8221;. If you are only calculating values from props or state, or handling a user event, you usually do not need an effect.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q45. What does the dependency array in useEffect control?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The dependency array tells React when to re-run the effect. React compares each value with the one from the last render, and runs the effect again only if something changed.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Dependency array<\/th><th>When the effect runs<\/th><\/tr><\/thead><tbody><tr><td>Not given<\/td><td>After every render<\/td><\/tr><tr><td><code>[]<\/code> (empty)<\/td><td>Once after the first render (mount), cleanup on unmount<\/td><\/tr><tr><td><code>[userId, page]<\/code><\/td><td>After the first render, and whenever <code>userId<\/code> or <code>page<\/code> changes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">You must list every prop, state and function from the component that the effect uses. Leaving one out causes bugs with stale values, and the hooks lint rule warns you about it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q46. What happens if you leave the dependency array out?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then the effect runs after every single render of the component. That is sometimes what you want, but often it is a mistake.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The classic bug is an effect that fetches data and stores it in state with no dependency array. Setting state causes a re-render, which runs the effect again, which sets state again, so you get an endless loop of requests. Always think about what the effect depends on and give the right array.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q47. What is a cleanup function in useEffect?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An effect can return a function, called the cleanup. React runs it before the effect runs again and when the component is removed (unmounts). It undoes what the effect set up, so you do not leak timers, subscriptions or network work.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>useEffect(() =&gt; {\n  const id = setInterval(() =&gt; setSeconds((s) =&gt; s + 1), 1000);\n  return () =&gt; clearInterval(id); \/\/ stop the timer\n}, []);\n\nuseEffect(() =&gt; {\n  const socket = connect(roomId);\n  return () =&gt; socket.disconnect(); \/\/ leave the old room before joining a new one\n}, [roomId]);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q48. Why does an effect run twice in development with Strict Mode?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In development only, Strict Mode mounts each component, then unmounts it and mounts it again. So your effect runs, its cleanup runs, and then the effect runs again. This does not happen in production.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React does this on purpose to help you find effects without proper cleanup. If running it twice causes a bug, such as two subscriptions or two chat connections, your cleanup is missing or wrong. The fix is to write correct cleanup, not to remove Strict Mode.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q49. What is the difference between useEffect and useLayoutEffect?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both run after React updates the DOM, but at different times. <code>useEffect<\/code> runs after the browser has painted the screen, so it does not block what the user sees. <code>useLayoutEffect<\/code> runs after the DOM update but before the browser paints, and it blocks painting until it finishes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>useLayoutEffect<\/code> only when you must measure the layout and change something before the user sees it, such as positioning a tooltip based on its size, to avoid a flicker. For everything else, use <code>useEffect<\/code>, because <code>useLayoutEffect<\/code> can slow down rendering.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q50. What does useRef do, and how is it different from state?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useRef<\/code> gives you a box (<code>{ current: value }<\/code>) that keeps its value between renders. Changing <code>ref.current<\/code> does not cause a re-render. It is used for two main things: holding a reference to a DOM element, and keeping a value that should not trigger renders, such as a timer ID.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function SearchBox() {\n  const inputRef = useRef(null);\n  return (\n    &lt;&gt;\n      &lt;input ref={inputRef} \/&gt;\n      &lt;button onClick={() =&gt; inputRef.current.focus()}&gt;Focus&lt;\/button&gt;\n    &lt;\/&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>useState<\/th><th>useRef<\/th><\/tr><\/thead><tbody><tr><td>Change causes re-render<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Read during render<\/td><td>Yes, it is meant for UI<\/td><td>Avoid, values can be out of date<\/td><\/tr><tr><td>Typical use<\/td><td>Data shown on screen<\/td><td>DOM nodes, timer IDs, previous values<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q51. What does useMemo do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useMemo<\/code> caches the result of a calculation between renders. React recalculates it only when one of its dependencies changes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const visibleProducts = useMemo(\n  () =&gt; products.filter((p) =&gt; p.name.toLowerCase().includes(query.toLowerCase())),\n  [products, query]\n);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It is used for expensive calculations, such as filtering or sorting thousands of items, and to keep the same object or array identity so memoised children or effects do not run again. It is a performance tool, so your code should still work correctly without it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q52. What does useCallback do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useCallback<\/code> caches a function between renders, so you get the same function object until its dependencies change. Normally, a function defined in a component is a new object on every render.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const handleAdd = useCallback((id) =&gt; {\n  setCart((c) =&gt; [...c, id]);\n}, []);\n\nreturn &lt;ProductList onAdd={handleAdd} \/&gt;; \/\/ ProductList is wrapped in React.memo<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It is mainly useful when you pass a function to a child wrapped in <code>React.memo<\/code>, or when a function is a dependency of an effect. <code>useCallback(fn, deps)<\/code> is the same as <code>useMemo(() =&gt; fn, deps)<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q53. When is useMemo or useCallback a waste?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They have a cost: extra code, memory for the cache and comparing dependencies on every render. So they are a waste when there is nothing to gain.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Cheap work:<\/strong> the calculation is small, such as adding two numbers or filtering 20 items.<\/li>\n\n\n<li><strong>No memoised user:<\/strong> the function or value is not passed to a memoised child or used as an effect dependency.<\/li>\n\n\n<li><strong>Changing inputs:<\/strong> the dependencies change on every render anyway, so the cache never helps.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Measure with the React DevTools Profiler first. Also, the React Compiler now adds memoization automatically, so in projects that use it, you rarely need to write these hooks by hand.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q54. What does useContext do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useContext<\/code> reads a value from a React Context, so any component deep in the tree can get shared data without prop drilling. You create a context, wrap part of the tree in its provider with a value, and read it where needed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const ThemeContext = createContext(\"light\");\n\nfunction App() {\n  const [theme, setTheme] = useState(\"dark\");\n  return (\n    &lt;ThemeContext value={theme}&gt;   {\/* React 19: use the context directly as a provider *\/}\n      &lt;Page \/&gt;\n    &lt;\/ThemeContext&gt;\n  );\n}\n\nfunction Button() {\n  const theme = useContext(ThemeContext);\n  return &lt;button className={`btn-${theme}`}&gt;Save&lt;\/button&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When the provider&#8217;s value changes, every component that reads that context re-renders.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q55. What is useReducer, and when is it better than useState?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useReducer<\/code> manages state with a reducer function: <code>(state, action) =&gt; newState<\/code>. You send actions with <code>dispatch<\/code>, and the reducer decides how the state changes. It is the same idea as Redux, but local to one component.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function cartReducer(state, action) {\n  switch (action.type) {\n    case \"add\":\n      return [...state, action.item];\n    case \"remove\":\n      return state.filter((i) =&gt; i.id !== action.id);\n    case \"clear\":\n      return [];\n    default:\n      return state;\n  }\n}\n\nconst [cart, dispatch] = useReducer(cartReducer, []);\ndispatch({ type: \"add\", item: { id: 7, name: \"Pen\" } });<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It is better than <code>useState<\/code> when state has many related fields, when the next state depends on complex rules, or when many event handlers change the same state. The reducer is a pure function, so it is easy to test.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q56. What is a custom hook?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A custom hook is your own function whose name starts with <code>use<\/code> and that calls other hooks. It lets you pull reusable logic out of components, such as fetching data, reading window size or handling a form.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function useOnlineStatus() {\n  const [online, setOnline] = useState(navigator.onLine);\n  useEffect(() =&gt; {\n    const goOnline = () =&gt; setOnline(true);\n    const goOffline = () =&gt; setOnline(false);\n    window.addEventListener(\"online\", goOnline);\n    window.addEventListener(\"offline\", goOffline);\n    return () =&gt; {\n      window.removeEventListener(\"online\", goOnline);\n      window.removeEventListener(\"offline\", goOffline);\n    };\n  }, []);\n  return online;\n}\n\nfunction StatusBar() {\n  const online = useOnlineStatus();\n  return &lt;p&gt;{online ? \"Online\" : \"Offline\"}&lt;\/p&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q57. Can two components that use the same custom hook share state?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. A custom hook shares logic, not state. Each component that calls the hook gets its own separate state, just as if it had called <code>useState<\/code> itself. So two components using <code>useCounter()<\/code> each have their own count.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To share the actual data, lift the state to a common parent, put it in a Context, or use a store like Zustand. A custom hook can read from such a shared store, which gives the effect of shared state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q58. What does useId do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useId<\/code> creates a unique ID that stays the same between renders and matches between server and client rendering. It is mainly used to connect form labels and inputs, and for accessibility attributes like <code>aria-describedby<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function EmailField() {\n  const id = useId();\n  return (\n    &lt;&gt;\n      &lt;label htmlFor={id}&gt;Email&lt;\/label&gt;\n      &lt;input id={id} type=\"email\" \/&gt;\n    &lt;\/&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Do not use it for list keys. Keys should come from your data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q59. What do useTransition and useDeferredValue do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both help keep the UI responsive during heavy updates, using concurrent rendering. They let React treat some updates as less urgent, so typing and clicking stay smooth.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>useTransition<\/strong> marks a state update as a transition. React can pause it to handle urgent updates first, and gives you <code>isPending<\/code> to show a loading hint.<\/li>\n\n\n<li><strong>useDeferredValue<\/strong> gives you a &#8220;lagging&#8221; copy of a value. The urgent part, such as the input, updates at once, while the slow part, such as a big list, uses the deferred value and catches up.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>const [query, setQuery] = useState(\"\");\nconst deferredQuery = useDeferredValue(query);\n\/\/ &lt;input value={query} onChange={e =&gt; setQuery(e.target.value)} \/&gt;\n\/\/ &lt;SlowResults query={deferredQuery} \/&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q60. What is useEffectEvent, and what problem does it solve?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useEffectEvent<\/code> (stable since React 19.2) lets you create an &#8220;effect event&#8221;: a function used inside an effect that always sees the latest props and state, but is not a dependency of the effect. It solves the problem where an effect re-runs just because a value it only reads, not reacts to, has changed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function ChatRoom({ roomId, theme }) {\n  const onConnected = useEffectEvent(() =&gt; {\n    showToast(\"Connected!\", theme); \/\/ always the latest theme\n  });\n\n  useEffect(() =&gt; {\n    const conn = createConnection(roomId);\n    conn.on(\"connected\", () =&gt; onConnected());\n    conn.connect();\n    return () =&gt; conn.disconnect();\n  }, [roomId]); \/\/ theme is not a dependency, so changing theme does not reconnect\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Without it, changing the theme would disconnect and reconnect the chat. Only call effect events from inside effects.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q61. What does the use API do in React 19?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>use<\/code> is a React 19 API that reads the value of a resource during render. It works with promises and with context. With a promise, the component &#8220;suspends&#8221; until the promise resolves, and the nearest <code>&lt;Suspense&gt;<\/code> shows a fallback meanwhile.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { use, Suspense } from \"react\";\n\nfunction Comments({ commentsPromise }) {\n  const comments = use(commentsPromise); \/\/ waits for the data\n  return comments.map((c) =&gt; &lt;p key={c.id}&gt;{c.text}&lt;\/p&gt;);\n}\n\n&lt;Suspense fallback={&lt;p&gt;Loading comments...&lt;\/p&gt;}&gt;\n  &lt;Comments commentsPromise={fetchComments(postId)} \/&gt;\n&lt;\/Suspense&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Unlike other hooks, <code>use<\/code> can be called inside conditions and loops. The promise should come from a framework, a cache or a Server Component, not be created fresh on every render.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q62. What does useActionState do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useActionState<\/code> (React 19) manages state for a form Action. You give it an action function and a starting state. It returns the current state, a wrapped action to use in the form, and an <code>isPending<\/code> flag.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async function subscribe(prevState, formData) {\n  const email = formData.get(\"email\");\n  const res = await fetch(\"\/api\/subscribe\", { method: \"POST\", body: JSON.stringify({ email }) });\n  return res.ok ? { message: \"Subscribed!\" } : { message: \"Something went wrong\" };\n}\n\nfunction NewsletterForm() {\n  const [state, formAction, isPending] = useActionState(subscribe, { message: \"\" });\n  return (\n    &lt;form action={formAction}&gt;\n      &lt;input name=\"email\" type=\"email\" required \/&gt;\n      &lt;button disabled={isPending}&gt;{isPending ? \"Saving...\" : \"Subscribe\"}&lt;\/button&gt;\n      &lt;p&gt;{state.message}&lt;\/p&gt;\n    &lt;\/form&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It removes a lot of manual <code>useState<\/code> code for loading flags, errors and results.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q63. What does useOptimistic do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useOptimistic<\/code> (React 19) shows the expected result of an action right away, before the server confirms it. If the action succeeds, the real data replaces the optimistic value. If it fails, React goes back to the real state automatically.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function LikeButton({ likes, likeAction }) {\n  const [optimisticLikes, addLike] = useOptimistic(likes, (current) =&gt; current + 1);\n\n  async function handleLike() {\n    addLike();          \/\/ the screen updates at once\n    await likeAction(); \/\/ then the server call finishes\n  }\n  return &lt;button onClick={() =&gt; startTransition(handleLike)}&gt;\u2764 {optimisticLikes}&lt;\/button&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This makes apps feel fast, for example in chat messages, likes and to-do items.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q64. What does useFormStatus do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>useFormStatus<\/code> (from <code>react-dom<\/code>, React 19) lets a component read the status of the form it is inside, such as whether it is submitting, without passing props down. It must be called from a component rendered inside a <code>&lt;form&gt;<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useFormStatus } from \"react-dom\";\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus();\n  return &lt;button disabled={pending}&gt;{pending ? \"Saving...\" : \"Save\"}&lt;\/button&gt;;\n}\n\n&lt;form action={saveProfile}&gt;\n  &lt;input name=\"name\" \/&gt;\n  &lt;SubmitButton \/&gt;\n&lt;\/form&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It makes reusable form parts, like a submit button for a design system, easy to build.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q65. How do you fetch data with useEffect without race conditions?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A race condition happens when an older request finishes after a newer one, so the screen shows old data. For example, the user types &#8220;go&#8221;, then &#8220;golang&#8221;, and the slow &#8220;go&#8221; response arrives last. The fix is to ignore or cancel stale requests in the cleanup.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function useProducts(query) {\n  const [data, setData] = useState(null);\n  const [error, setError] = useState(null);\n\n  useEffect(() =&gt; {\n    const controller = new AbortController();\n    fetch(`\/api\/products?q=${encodeURIComponent(query)}`, { signal: controller.signal })\n      .then((res) =&gt; {\n        if (!res.ok) throw new Error(`HTTP ${res.status}`);\n        return res.json();\n      })\n      .then(setData)\n      .catch((err) =&gt; {\n        if (err.name !== \"AbortError\") setError(err);\n      });\n    return () =&gt; controller.abort(); \/\/ cancel the old request\n  }, [query]);\n\n  return { data, error };\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In real apps, prefer a data library such as TanStack Query or your framework&#8217;s data loading, which handles caching, retries and races for you.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Rendering and Performance React JS Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Senior candidates are judged on how well they understand rendering. These React JS interview questions go deeper into when and why components re-render, and how to make apps fast.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q66. What causes a component to re-render?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A component re-renders in these situations.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Its own state changes, through a <code>useState<\/code> setter or <code>useReducer<\/code> dispatch.<\/li>\n\n\n<li>Its parent re-renders, which by default re-renders all its children.<\/li>\n\n\n<li>A context it reads with <code>useContext<\/code> gets a new value.<\/li>\n\n\n<li>A custom hook it uses changes its internal state.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">&#8220;Re-render&#8221; means React calls your component function again to get new JSX. It does not mean the real DOM changes. React only updates the DOM where the result is different. Changing a normal variable or a ref does not cause a re-render.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q67. Does a parent re-render always re-render its children?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default, yes. When a parent re-renders, React re-renders every child component in its JSX, even if their props did not change. Usually this is fast enough and not a problem.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are exceptions. A child wrapped in <code>React.memo<\/code> skips re-rendering if its props are the same. Elements passed in as <code>children<\/code> or other props from higher up are not re-rendered just because the wrapper&#8217;s state changed. The React Compiler also skips unchanged children automatically. So moving state down, closer to where it is used, is a simple way to avoid extra renders.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q68. What is React.memo?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>React.memo<\/code> wraps a component and tells React to skip re-rendering it when its props have not changed. React compares each prop with a shallow equality check (<code>Object.is<\/code>).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const ProductRow = React.memo(function ProductRow({ product, onAdd }) {\n  return (\n    &lt;tr&gt;\n      &lt;td&gt;{product.name}&lt;\/td&gt;\n      &lt;td&gt;&lt;button onClick={() =&gt; onAdd(product.id)}&gt;Add&lt;\/button&gt;&lt;\/td&gt;\n    &lt;\/tr&gt;\n  );\n});<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use it for components that render often with the same props and are expensive to render, such as rows in a big table. Do not wrap everything, because the prop comparison itself has a small cost.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q69. Why can a new object or function passed as a prop break React.memo?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>React.memo<\/code> compares props by reference. A function, object or array created inside the parent&#8217;s render is a brand-new value every time, even if it looks the same. So the comparison sees a &#8220;changed&#8221; prop and the memoised child re-renders anyway.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function Parent() {\n  const [count, setCount] = useState(0);\n  \/\/ New function and new object on every render: ProductRow always re-renders\n  return &lt;ProductRow onAdd={(id) =&gt; addToCart(id)} style={{ color: \"red\" }} \/&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The fix is to keep the same reference with <code>useCallback<\/code> for functions and <code>useMemo<\/code> for objects, or move constant objects outside the component. The React Compiler does this for you automatically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q70. What is the React Compiler, and how does it change manual memoization?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The React Compiler is a build-time tool, stable since late 2025, that automatically optimises your components and hooks. It analyses your code and adds memoization where it helps, so components and values are only recalculated when their inputs really change.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This means you rarely need to write <code>useMemo<\/code>, <code>useCallback<\/code> or <code>React.memo<\/code> by hand. The code stays simpler, and performance is often better than manual memoization. It works best when your code follows the rules of React, such as not changing props or state directly, so the ESLint plugin helps you spot code the compiler cannot optimise. You add it as a Babel or build plugin, and frameworks like Next.js and Vite templates support it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q71. What is batching of state updates?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Batching means React groups several state updates into one re-render instead of re-rendering after each one. Since React 18, this happens automatically everywhere: in event handlers, promises, <code>setTimeout<\/code> and native events.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function handleClick() {\n  setName(\"Asha\");\n  setAge(30);\n  setCity(\"Pune\");\n  \/\/ Only one re-render happens, after the handler finishes\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This makes apps faster and avoids showing half-updated UI. In the rare case you need the DOM updated at once, such as before measuring it, you can use <code>flushSync<\/code> from <code>react-dom<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q72. What is code splitting?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Code splitting means breaking your JavaScript bundle into smaller chunks that load only when needed, instead of one big file at the start. For example, the admin page or a heavy chart library loads only when a user opens that page.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes the first page load faster, especially on slow mobile networks. Bundlers like Vite and webpack split code automatically at dynamic <code>import()<\/code> calls, and React frameworks split by route for you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q73. What do React.lazy and Suspense do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>React.lazy<\/code> loads a component&#8217;s code only when it is first rendered. <code>Suspense<\/code> shows a fallback, such as a spinner, while that code (or data) is loading.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { lazy, Suspense } from \"react\";\n\nconst ReportsPage = lazy(() =&gt; import(\".\/ReportsPage\"));\n\nfunction App() {\n  return (\n    &lt;Suspense fallback={&lt;p&gt;Loading reports...&lt;\/p&gt;}&gt;\n      &lt;ReportsPage \/&gt;\n    &lt;\/Suspense&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Suspense<\/code> also works with data loading through <code>use<\/code>, Server Components and libraries that support it. You can place several <code>Suspense<\/code> boundaries, so parts of the page appear as soon as they are ready.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q74. What is an error boundary, and why is it still a class component?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An error boundary is a component that catches JavaScript errors in its child tree during rendering, shows a fallback UI instead of a blank screen, and can log the error. It does not catch errors in event handlers, async code or the boundary itself.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ErrorBoundary extends React.Component {\n  state = { hasError: false };\n  static getDerivedStateFromError() {\n    return { hasError: true };\n  }\n  componentDidCatch(error, info) {\n    logErrorToService(error, info.componentStack);\n  }\n  render() {\n    return this.state.hasError ? &lt;p&gt;Something went wrong.&lt;\/p&gt; : this.props.children;\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It still needs a class because React has no hook for <code>getDerivedStateFromError<\/code> and <code>componentDidCatch<\/code> yet. Most teams use the small <code>react-error-boundary<\/code> package, which gives a ready-made component with a reset feature.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q75. What is a portal, and when do you need one?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A portal lets a component render its children into a different DOM node, outside its parent&#8217;s DOM hierarchy, while still behaving like a normal React child for state, context and events.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { createPortal } from \"react-dom\";\n\nfunction Modal({ children }) {\n  return createPortal(\n    &lt;div className=\"modal-backdrop\"&gt;{children}&lt;\/div&gt;,\n    document.body\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You need one for modals, tooltips, dropdowns and toasts. If they are rendered inside a parent with <code>overflow: hidden<\/code> or a low <code>z-index<\/code>, they get cut off or hidden. A portal moves them to the end of <code>body<\/code>, so they appear on top.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q76. What is Strict Mode, and what does it check?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>&lt;StrictMode&gt;<\/code> is a development-only helper that wraps your app and finds common bugs early. Production builds ignore it.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Double rendering:<\/strong> components render twice to find impure rendering code.<\/li>\n\n\n<li><strong>Effect re-run:<\/strong> effects run, then clean up, then run again, to find missing cleanup.<\/li>\n\n\n<li><strong>Ref re-run:<\/strong> ref callbacks run twice to find missing ref cleanup.<\/li>\n\n\n<li><strong>Warnings:<\/strong> it warns about deprecated APIs.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">So if something breaks only in Strict Mode, it usually points to a real bug that would show up later, for example with fast navigation or Activity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q77. How do you find slow components with the React DevTools Profiler?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Install the React Developer Tools browser extension and open the Profiler tab. Click record, do the slow action in your app, such as typing in a search box, then stop recording.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Profiler shows each commit and a flame chart of which components rendered, how long each took and why it rendered (turn on &#8220;Record why each component rendered&#8221;). Look for components that render often or take a long time. Then fix the cause, such as moving state down, splitting a big component, memoising, virtualising a long list or using a transition. Browser performance tools and React Performance Tracks give even more detail.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q78. What is list virtualisation, and when do you need it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">List virtualisation (or windowing) means rendering only the list items that are visible on screen, plus a few extra, instead of all of them. As the user scrolls, items are swapped in and out. So a list of 10,000 rows only has about 20 rows in the DOM at a time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You need it when you show very long lists or tables and scrolling or typing becomes slow. Libraries like TanStack Virtual and react-window make it easy. For short lists, it is not worth the extra complexity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q79. What is concurrent rendering?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Concurrent rendering, added in React 18, means React can prepare several versions of the UI at the same time and pause, resume or drop rendering work. Before this, rendering was one blocking task that ran until it finished.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So React can handle urgent updates first, such as typing, while slower updates, such as a filtered list, render in the background. You turn this on for specific updates with <code>useTransition<\/code>, <code>useDeferredValue<\/code> and <code>Suspense<\/code>. It keeps apps responsive even when some screens are expensive to render.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q80. What is hydration, and what is a hydration mismatch?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With server rendering, the server sends ready HTML so the page appears fast. Hydration is when React runs in the browser, builds the same component tree, and attaches event handlers and state to that existing HTML, making it interactive.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A hydration mismatch happens when the HTML React renders in the browser is different from what the server sent. Common causes are using <code>Date.now()<\/code>, <code>Math.random()<\/code>, <code>window<\/code> or <code>localStorage<\/code> during render, or invalid HTML nesting like a <code>div<\/code> inside a <code>p<\/code>. React then shows a warning and may re-render that part. Fix it by rendering the same output on both sides, and moving browser-only values into <code>useEffect<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Routing, Forms and Data React JS Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Real apps need pages, forms and data from a backend. These React JS interview questions cover the tools and patterns you will use every day.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q81. How does client-side routing work?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In client-side routing, the browser loads the app once, and JavaScript changes what is shown when the URL changes, without asking the server for a new HTML page. The router listens to URL changes using the browser History API, matches the URL to a route, and renders the matching component.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { BrowserRouter, Routes, Route, Link } from \"react-router\";\n\nfunction App() {\n  return (\n    &lt;BrowserRouter&gt;\n      &lt;nav&gt;\n        &lt;Link to=\"\/\"&gt;Home&lt;\/Link&gt; | &lt;Link to=\"\/products\"&gt;Products&lt;\/Link&gt;\n      &lt;\/nav&gt;\n      &lt;Routes&gt;\n        &lt;Route path=\"\/\" element={&lt;Home \/&gt;} \/&gt;\n        &lt;Route path=\"\/products\" element={&lt;Products \/&gt;} \/&gt;\n        &lt;Route path=\"\/products\/:id\" element={&lt;ProductDetail \/&gt;} \/&gt;\n        &lt;Route path=\"*\" element={&lt;NotFound \/&gt;} \/&gt;\n      &lt;\/Routes&gt;\n    &lt;\/BrowserRouter&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Link<\/code> changes the URL without a page reload. The server must also send the app&#8217;s HTML for any path, so direct visits and refreshes work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q82. How do you read URL parameters in React Router?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>useParams<\/code> for path parameters, such as <code>\/products\/:id<\/code>, and <code>useSearchParams<\/code> for the query string, such as <code>?sort=price&amp;page=2<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useParams, useSearchParams } from \"react-router\";\n\nfunction ProductDetail() {\n  const { id } = useParams();                         \/\/ \"\/products\/42\" -&gt; \"42\"\n  const [searchParams, setSearchParams] = useSearchParams();\n  const tab = searchParams.get(\"tab\") ?? \"details\";   \/\/ \"?tab=reviews\"\n\n  return (\n    &lt;div&gt;\n      &lt;h1&gt;Product {id}&lt;\/h1&gt;\n      &lt;button onClick={() =&gt; setSearchParams({ tab: \"reviews\" })}&gt;Reviews&lt;\/button&gt;\n      &lt;p&gt;Showing: {tab}&lt;\/p&gt;\n    &lt;\/div&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Values from the URL are always strings, so convert them, such as <code>Number(id)<\/code>, and validate them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q83. How do you protect a route that needs login?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Wrap protected routes in a component that checks if the user is logged in, and redirects to the login page if not.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { Navigate, Outlet, useLocation } from \"react-router\";\n\nfunction RequireAuth() {\n  const { user } = useAuth();\n  const location = useLocation();\n  if (!user) {\n    return &lt;Navigate to=\"\/login\" replace state={{ from: location }} \/&gt;;\n  }\n  return &lt;Outlet \/&gt;; \/\/ render the child routes\n}\n\n\/\/ &lt;Route element={&lt;RequireAuth \/&gt;}&gt;\n\/\/   &lt;Route path=\"\/orders\" element={&lt;Orders \/&gt;} \/&gt;\n\/\/ &lt;\/Route&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Remember that this only protects the UI. The real security must be on the server: every API call must check the user&#8217;s token and permissions, because anyone can change front-end code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q84. How do you handle forms with many fields?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For many fields, avoid one <code>useState<\/code> per field. Here are good options.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>One state object:<\/strong> keep all values in one object and use a single <code>onChange<\/code> that uses the input&#8217;s <code>name<\/code>.<\/li>\n\n\n<li><strong>useReducer:<\/strong> for forms with complex rules between fields.<\/li>\n\n\n<li><strong>Uncontrolled inputs with FormData:<\/strong> read all values on submit, which works well with React 19 form Actions.<\/li>\n\n\n<li><strong>A form library:<\/strong> such as React Hook Form, for validation, errors and big forms.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>function SignupForm() {\n  const [form, setForm] = useState({ name: \"\", email: \"\", city: \"\" });\n\n  function handleChange(e) {\n    const { name, value } = e.target;\n    setForm((f) =&gt; ({ ...f, [name]: value }));\n  }\n\n  return (\n    &lt;form&gt;\n      &lt;input name=\"name\" value={form.name} onChange={handleChange} \/&gt;\n      &lt;input name=\"email\" value={form.email} onChange={handleChange} \/&gt;\n      &lt;input name=\"city\" value={form.city} onChange={handleChange} \/&gt;\n    &lt;\/form&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q85. When would you use a form library such as React Hook Form?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use a form library when forms get big or complex: many fields, field-level validation, error messages, dynamic fields (such as adding more addresses), multi-step wizards, or dependent fields. React Hook Form is popular because it uses uncontrolled inputs, so typing does not re-render the whole form, which keeps big forms fast.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It pairs well with schema validation libraries like Zod, so the same rules can validate data on the client and the server. For a simple login or contact form, plain React or React 19 Actions are usually enough.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q86. What is the Context API, and when is it not enough?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Context API shares values with many components without passing props through every level. It is ideal for data that changes rarely and is needed in many places, such as the theme, language, current user or a feature flag.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is not enough when shared state changes often and many components read it. Every component that uses the context re-renders when the value changes, even if it only needs one small part. It also has no built-in tools for caching server data, devtools or selectors. For those cases, use a state library with selectors (such as Zustand or Redux Toolkit) or a server state library (such as TanStack Query).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q87. When would you use Redux Toolkit, Zustand or another state library?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You need a global state library when lots of client state is shared across distant parts of the app, changes often, and needs clear rules. Examples are a complex editor, a multi-step booking flow or a dashboard with many filters.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Library<\/th><th>Good for<\/th><th>Style<\/th><\/tr><\/thead><tbody><tr><td>Redux Toolkit<\/td><td>Large apps, strict patterns, strong devtools<\/td><td>Store, slices, actions, reducers<\/td><\/tr><tr><td>Zustand<\/td><td>Small to medium apps wanting simple global state<\/td><td>Small hook-based store<\/td><\/tr><tr><td>Jotai<\/td><td>Fine-grained shared state<\/td><td>Small independent atoms<\/td><\/tr><tr><td>Context + useReducer<\/td><td>Simple shared state, no extra library<\/td><td>Built into React<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Many apps need much less global state than they think, because most &#8220;global&#8221; data is actually server state, which is better handled by TanStack Query or framework data loading.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q88. What is server state, and why do tools like TanStack Query exist?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Server state is data that lives on the server and is shown in your app, such as products, orders and user profiles. It is different from client state (such as an open menu), because it can change without your app knowing, it needs fetching and it can be out of date.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Handling it with <code>useEffect<\/code> and <code>useState<\/code> means writing a lot of code for loading states, errors, caching, retries, refetching, pagination and avoiding duplicate requests. TanStack Query (React Query) and SWR do all of this for you.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useQuery } from \"@tanstack\/react-query\";\n\nfunction Orders() {\n  const { data, isPending, error } = useQuery({\n    queryKey: [\"orders\"],\n    queryFn: () =&gt; fetch(\"\/api\/orders\").then((r) =&gt; r.json()),\n    staleTime: 60_000, \/\/ treat data as fresh for 1 minute\n  });\n  if (isPending) return &lt;p&gt;Loading...&lt;\/p&gt;;\n  if (error) return &lt;p&gt;Could not load orders.&lt;\/p&gt;;\n  return data.map((o) =&gt; &lt;p key={o.id}&gt;{o.id}: \u20b9{o.total}&lt;\/p&gt;);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q89. How do you show loading and error states while data loads?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Every data request has three states: loading, error and success. Show a clear UI for each, so users are never left with a blank screen.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function UserProfile({ userId }) {\n  const { data: user, isPending, error, refetch } = useUser(userId);\n\n  if (isPending) return &lt;Spinner label=\"Loading profile\" \/&gt;;\n  if (error) {\n    return (\n      &lt;div role=\"alert\"&gt;\n        &lt;p&gt;Could not load the profile.&lt;\/p&gt;\n        &lt;button onClick={() =&gt; refetch()}&gt;Try again&lt;\/button&gt;\n      &lt;\/div&gt;\n    );\n  }\n  return &lt;h1&gt;{user.name}&lt;\/h1&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">With <code>Suspense<\/code>, you can move loading UI into a <code>&lt;Suspense fallback={...}&gt;<\/code> boundary and errors into an error boundary. Skeleton screens that look like the final layout often feel faster than spinners.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q90. How do you store a login token safely in a React app?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The safest common approach is to keep the session token in an <code>HttpOnly<\/code>, <code>Secure<\/code>, <code>SameSite<\/code> cookie set by the server. JavaScript cannot read an HttpOnly cookie, so a cross-site scripting (XSS) bug cannot steal it. Add CSRF protection, such as <code>SameSite=Lax<\/code> or <code>Strict<\/code> plus CSRF tokens for risky requests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Storing tokens in <code>localStorage<\/code> is simple but risky, because any XSS bug or bad third-party script can read and steal them. If you must hold a token in JavaScript, such as an access token for an API, keep it in memory only, keep it short-lived, and get new ones with a refresh token stored in an HttpOnly cookie. Also, prevent XSS in the first place: do not use <code>dangerouslySetInnerHTML<\/code> with user input, and add a Content Security Policy.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Modern React and Testing React JS Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">React 19 added several features that interviewers now ask about. These React JS interview questions cover them, plus testing, accessibility, TypeScript and linting.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q91. What are Server Components?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React Server Components (RSC) are components that run only on the server, either at build time or for each request. They can read from a database, the file system or private APIs directly, and they send the finished UI to the browser without sending their own JavaScript code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ app\/products\/page.jsx (Next.js App Router): a Server Component by default\nexport default async function ProductsPage() {\n  const products = await db.product.findMany(); \/\/ runs only on the server\n  return (\n    &lt;ul&gt;\n      {products.map((p) =&gt; &lt;li key={p.id}&gt;{p.name}&lt;\/li&gt;)}\n    &lt;\/ul&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The benefits are a smaller JavaScript bundle, faster first loads, simple data fetching with <code>async<\/code>\/<code>await<\/code>, and secrets that stay on the server. You use them through a framework that supports them, such as Next.js. Keep the framework and React packages up to date, because server-side features have had serious security fixes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q92. What is the difference between a Server Component and a Client Component?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Server Components run on the server and send rendered output. Client Components are the &#8220;normal&#8221; React components you already know. They are also rendered on the server for the first HTML, but their code is sent to the browser, so they can be interactive.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Server Component<\/th><th>Client Component<\/th><\/tr><\/thead><tbody><tr><td>Runs on<\/td><td>Server only<\/td><td>Server for first HTML, then browser<\/td><\/tr><tr><td>JavaScript sent to browser<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>State and effects (<code>useState<\/code>, <code>useEffect<\/code>)<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Event handlers (<code>onClick<\/code>)<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Direct database or secret access<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Marked with<\/td><td>Default in RSC frameworks<\/td><td><code>\"use client\"<\/code> at the top of the file<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A good pattern is to keep pages and data loading in Server Components, and make small leaf components, like a &#8220;Like&#8221; button or a search box, Client Components.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q93. What does the &#8220;use client&#8221; directive do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>\"use client\"<\/code> is a line at the very top of a file that marks the boundary between Server and Client Components. It tells the bundler that this module, and everything it imports, runs on the client and must be included in the browser bundle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You add it to components that use state, effects, event handlers or browser APIs. You do not need it in every client file, only at the entry points where Server Components import client code. It does not mean &#8220;render only in the browser&#8221;, because client components are still pre-rendered to HTML on the server.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q94. What are Server Functions (Server Actions)?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Server Functions are async functions that run on the server but can be called from client code, like a normal function. They are marked with the <code>\"use server\"<\/code> directive. When used as form actions or inside transitions, they are often called Server Actions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ actions.js\n\"use server\";\n\nexport async function addToCart(formData) {\n  const productId = formData.get(\"productId\");\n  const user = await getSessionUser();      \/\/ always check auth on the server\n  await db.cart.add(user.id, productId);\n}\n\n\/\/ In a component\n&lt;form action={addToCart}&gt;\n  &lt;input type=\"hidden\" name=\"productId\" value=\"42\" \/&gt;\n  &lt;button&gt;Add to cart&lt;\/button&gt;\n&lt;\/form&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The framework creates the network call for you. Treat every Server Function like a public API endpoint: check authentication, permissions and input, because anyone can call it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q95. What are Actions in React 19, and how do they help forms?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In React 19, an Action is an async function used in a transition, often passed to a form&#8217;s <code>action<\/code> prop. React then handles the boring parts for you: pending state, errors, optimistic updates and resetting the form after a successful submit.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function UpdateName() {\n  const [error, submitAction, isPending] = useActionState(async (prev, formData) =&gt; {\n    const result = await updateName(formData.get(\"name\"));\n    return result.error ?? null;\n  }, null);\n\n  return (\n    &lt;form action={submitAction}&gt;\n      &lt;input name=\"name\" \/&gt;\n      &lt;button disabled={isPending}&gt;Update&lt;\/button&gt;\n      {error &amp;&amp; &lt;p role=\"alert\"&gt;{error}&lt;\/p&gt;}\n    &lt;\/form&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Together with <code>useActionState<\/code>, <code>useFormStatus<\/code> and <code>useOptimistic<\/code>, Actions remove a lot of manual <code>useState<\/code> code, and forms can even work before JavaScript loads when used with server rendering.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q96. How can you pass ref as a normal prop in React 19?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Since React 19, function components can receive <code>ref<\/code> as a normal prop. You no longer need to wrap them in <code>forwardRef<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ React 19\nfunction TextInput({ label, ref, ...props }) {\n  return (\n    &lt;label&gt;\n      {label}\n      &lt;input ref={ref} {...props} \/&gt;\n    &lt;\/label&gt;\n  );\n}\n\nfunction Form() {\n  const inputRef = useRef(null);\n  return &lt;TextInput label=\"Name\" ref={inputRef} \/&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>forwardRef<\/code> still works but will be deprecated in the future. React 19 also lets ref callbacks return a cleanup function, which runs when the element is removed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q97. What is the Activity component?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>&lt;Activity&gt;<\/code> (stable since React 19.2) lets you hide and show parts of the UI while keeping their state. It has two modes: <code>visible<\/code> and <code>hidden<\/code>. When hidden, the content is hidden from the screen, its effects are cleaned up, and its updates get low priority, but its state stays in memory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;Activity mode={activeTab === \"settings\" ? \"visible\" : \"hidden\"}&gt;\n  &lt;SettingsPanel \/&gt;\n&lt;\/Activity&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is useful for tabs, so a half-filled form or scroll position is not lost when switching tabs. You can also pre-render a screen the user is likely to open next in the background.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q98. What is the difference between SSR, SSG and CSR?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These are three ways to render a React page.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Method<\/th><th>When HTML is made<\/th><th>Good for<\/th><th>Trade-off<\/th><\/tr><\/thead><tbody><tr><td>CSR (client-side rendering)<\/td><td>In the browser, after JavaScript loads<\/td><td>Dashboards behind login<\/td><td>Slow first paint, weak SEO<\/td><\/tr><tr><td>SSR (server-side rendering)<\/td><td>On the server, for each request<\/td><td>Personalised, frequently changing pages with SEO<\/td><td>Server work on every request<\/td><\/tr><tr><td>SSG (static site generation)<\/td><td>At build time<\/td><td>Blogs, docs, marketing pages<\/td><td>Data can be out of date until rebuilt<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Modern frameworks mix them per page, and add incremental regeneration and streaming SSR with <code>Suspense<\/code>, which sends parts of the page as soon as they are ready.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q99. How do you test a component with React Testing Library?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">React Testing Library (RTL) renders your component and lets you interact with it the way a user would: find elements by role, label or text, click, type and check what appears. It usually runs with Vitest or Jest, plus <code>@testing-library\/user-event<\/code> for realistic interactions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { render, screen } from \"@testing-library\/react\";\nimport userEvent from \"@testing-library\/user-event\";\nimport Counter from \".\/Counter\";\n\ntest(\"increases the count when clicked\", async () =&gt; {\n  const user = userEvent.setup();\n  render(&lt;Counter \/&gt;);\n\n  await user.click(screen.getByRole(\"button\", { name: \/add\/i }));\n\n  expect(screen.getByText(\"Count: 1\")).toBeInTheDocument();\n});<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The idea is to test behaviour, not implementation details like state variables, so tests do not break when you refactor.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q100. Why should tests find elements by role or label instead of class names?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Users do not see class names or test IDs. They see buttons, links, headings and labelled inputs. Queries like <code>getByRole(\"button\", { name: \"Save\" })<\/code> and <code>getByLabelText(\"Email\")<\/code> find elements the same way users and screen readers do.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So your tests break only when the real user experience changes, not when you rename a CSS class. As a bonus, if a test cannot find an element by role or label, your UI probably has an accessibility problem. Use <code>getByTestId<\/code> only as a last resort.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q101. How do you mock an API call in a component test?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The most popular approach is Mock Service Worker (MSW). It catches network requests at the network level and returns fake responses, so your component&#8217;s real <code>fetch<\/code> code runs unchanged.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { http, HttpResponse } from \"msw\";\nimport { setupServer } from \"msw\/node\";\n\nconst server = setupServer(\n  http.get(\"\/api\/orders\", () =&gt;\n    HttpResponse.json([{ id: 1, total: 499 }])\n  )\n);\n\nbeforeAll(() =&gt; server.listen());\nafterEach(() =&gt; server.resetHandlers());\nafterAll(() =&gt; server.close());\n\ntest(\"shows orders\", async () =&gt; {\n  render(&lt;Orders \/&gt;);\n  expect(await screen.findByText(\/499\/)).toBeInTheDocument();\n});<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also mock a module with <code>vi.mock<\/code> or <code>jest.mock<\/code>, but MSW tests are closer to real behaviour, and the same mocks can be reused in development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q102. How do you test a custom hook?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>renderHook<\/code> from React Testing Library. It renders the hook inside a small test component and gives you its current return value.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { renderHook, act } from \"@testing-library\/react\";\nimport { useCounter } from \".\/useCounter\";\n\ntest(\"useCounter increments\", () =&gt; {\n  const { result } = renderHook(() =&gt; useCounter(5));\n\n  act(() =&gt; result.current.increment());\n\n  expect(result.current.count).toBe(6);\n});<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Wrap state changes in <code>act<\/code>, so React finishes updating before you check. If the hook needs a provider, such as a QueryClient or Context, pass a <code>wrapper<\/code> option. Often it is even better to test the hook through a component that uses it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q103. What is accessibility (a11y), and how do you make a React app accessible?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Accessibility means making your app usable by everyone, including people who use screen readers, keyboards only, voice control or who have low vision. &#8220;a11y&#8221; is short for the 11 letters between &#8220;a&#8221; and &#8220;y&#8221;. It is also a legal requirement in many places.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the key practices in React.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use semantic HTML: <code>button<\/code> for actions, <code>a<\/code> for links, <code>nav<\/code>, <code>main<\/code>, headings in order.<\/li>\n\n\n<li>Give every input a <code>label<\/code>, and images useful <code>alt<\/code> text.<\/li>\n\n\n<li>Make everything work with the keyboard, with visible focus styles.<\/li>\n\n\n<li>Manage focus in modals and after route changes, and trap focus inside open dialogs.<\/li>\n\n\n<li>Use ARIA attributes only when HTML cannot express it, such as <code>aria-expanded<\/code> on a menu button.<\/li>\n\n\n<li>Check colour contrast, and test with tools like axe, Lighthouse and <code>eslint-plugin-jsx-a11y<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q104. How do you add TypeScript types to props?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Define a <code>type<\/code> or <code>interface<\/code> for the props and use it in the component&#8217;s parameter. TypeScript then checks every place that uses the component.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type ButtonProps = {\n  label: string;\n  variant?: \"primary\" | \"secondary\";   \/\/ optional, only these two values\n  onClick: () =&gt; void;\n  children?: React.ReactNode;\n};\n\nfunction Button({ label, variant = \"primary\", onClick }: ButtonProps) {\n  return &lt;button className={`btn-${variant}`} onClick={onClick}&gt;{label}&lt;\/button&gt;;\n}\n\n\/\/ For native elements, extend their props:\ntype InputProps = React.ComponentProps&lt;\"input\"&gt; &amp; { label: string };<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Most teams no longer use <code>React.FC<\/code>, because plain typed functions are simpler. Hooks infer types too, and you can give them explicitly, such as <code>useState&lt;User | null&gt;(null)<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q105. How do you set up linting for hooks with ESLint?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Install <code>eslint-plugin-react-hooks<\/code>, the official plugin from the React team. Its rules check the rules of hooks and the dependency arrays of effects, and its newer rules also report code that breaks the rules of React, which the React Compiler needs.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ eslint.config.js (flat config)\nimport reactHooks from \"eslint-plugin-react-hooks\";\n\nexport default [\n  reactHooks.configs.flat.recommended,\n];<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Run ESLint in your editor and in CI. Treat <code>exhaustive-deps<\/code> warnings seriously, because a missing dependency is a common source of stale data bugs. Vite and framework templates usually include this setup already.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Scenario React JS Interview Questions with Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For each scenario, explain what you would check first, and why. Interviewers care more about your steps than a perfect answer, so these answers follow a clear &#8220;find, fix, prevent&#8221; order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q106. A page freezes when the user types in a search box. How do you fix it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, find what is slow. Record the typing in the React DevTools Profiler and the browser Performance panel. Usually, each key press re-renders a big list or runs an expensive filter.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then fix it with one or more of these steps.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Keep the input fast:<\/strong> use <code>useDeferredValue<\/code> (or <code>useTransition<\/code>) so the input updates at once and the heavy list renders in the background.<\/li>\n\n\n<li><strong>Debounce network calls:<\/strong> wait about 300 ms after typing stops before calling the API.<\/li>\n\n\n<li><strong>Make rendering cheaper:<\/strong> memoise the filtered list with <code>useMemo<\/code> (or rely on the React Compiler), and wrap list rows in <code>React.memo<\/code>.<\/li>\n\n\n<li><strong>Render less:<\/strong> virtualise long lists, so only visible rows are in the DOM.<\/li>\n\n\n<li><strong>Move state down:<\/strong> keep the search text in the search component, so the rest of the page does not re-render on each key.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>function Search({ products }) {\n  const [query, setQuery] = useState(\"\");\n  const deferredQuery = useDeferredValue(query);\n  return (\n    &lt;&gt;\n      &lt;input value={query} onChange={(e) =&gt; setQuery(e.target.value)} \/&gt;\n      &lt;ProductList products={products} query={deferredQuery} \/&gt;\n    &lt;\/&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q107. An effect fetches data in a loop and never stops. What is wrong?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The effect sets state, the state change causes a re-render, and the effect runs again, which sets state again, forever. There are a few usual causes.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No dependency array,<\/strong> so the effect runs after every render.<\/li>\n\n\n<li><strong>An object or array dependency created during render,<\/strong> such as <code>useEffect(..., [filters])<\/code> where <code>filters = { page: 1 }<\/code> is a new object every time.<\/li>\n\n\n<li><strong>A function dependency<\/strong> that is recreated on every render.<\/li>\n\n\n<li><strong>The effect sets a value it depends on,<\/strong> such as fetching and then updating the same <code>filters<\/code> state.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Fix it by giving the correct dependency array with primitive values (<code>[page, query]<\/code>), moving object creation inside the effect, using <code>useMemo<\/code> or <code>useCallback<\/code> for objects and functions, or using a data library like TanStack Query. The network tab in DevTools shows the repeated calls clearly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q108. A list shows the wrong item after you delete one row. Why?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is almost always a key problem. The list probably uses the array index as the key, <code>key={index}<\/code>. When you delete row 2, every row after it moves up one index, so React thinks row 2 still exists with new data and keeps the old DOM and state (such as an input&#8217;s text or a checkbox) on the wrong item.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bug\n{items.map((item, index) =&gt; &lt;Row key={index} item={item} \/&gt;)}\n\n\/\/ Fix: a stable, unique ID from the data\n{items.map((item) =&gt; &lt;Row key={item.id} item={item} \/&gt;)}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the data has no ID, create one when the item is created, such as <code>crypto.randomUUID()<\/code>, never during render.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q109. Your app bundle is 3 MB and loads slowly. How do you shrink it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, measure what is inside. Use a bundle analyser, such as <code>rollup-plugin-visualizer<\/code> for Vite or <code>@next\/bundle-analyzer<\/code> for Next.js, to see which packages are biggest.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then shrink it step by step.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Code split by route<\/strong> with <code>React.lazy<\/code> and dynamic <code>import()<\/code>, so each page loads its own code.<\/li>\n\n\n<li><strong>Lazy load heavy features,<\/strong> such as charts, editors and maps, only when used.<\/li>\n\n\n<li><strong>Replace heavy libraries,<\/strong> such as moment.js with date-fns or <code>Intl<\/code>, and import only what you use (<code>lodash-es\/debounce<\/code> instead of all of lodash).<\/li>\n\n\n<li><strong>Remove unused code and duplicate packages,<\/strong> and check that tree shaking works.<\/li>\n\n\n<li><strong>Use Server Components<\/strong> in a framework, so server-only code never reaches the browser.<\/li>\n\n\n<li><strong>Optimise assets:<\/strong> compress images, use modern formats, and serve everything with compression and caching from a CDN.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, set a bundle size budget in CI, so it does not grow back.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q110. Design the component structure for a shopping cart page.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Split the page into small components with clear jobs, keep server data in a data library, and keep cart state in one place.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>CartPage                      \/\/ route page: loads cart data, handles layout\n\u251c\u2500\u2500 CartHeader                \/\/ title and item count\n\u251c\u2500\u2500 CartItemList              \/\/ maps items to rows\n\u2502   \u2514\u2500\u2500 CartItemRow           \/\/ image, name, price, QuantitySelector, remove button\n\u2502       \u2514\u2500\u2500 QuantitySelector  \/\/ + and - buttons, calls onChange(newQty)\n\u251c\u2500\u2500 CouponForm                \/\/ input + apply button (form Action)\n\u251c\u2500\u2500 OrderSummary              \/\/ subtotal, discount, tax, total (derived values)\n\u2514\u2500\u2500 CheckoutButton            \/\/ disabled when cart is empty or updating<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the key decisions to explain.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>State:<\/strong> the cart lives on the server and is read with TanStack Query or a Server Component. Updates go through mutations or Server Actions, with <code>useOptimistic<\/code> so quantity changes feel instant.<\/li>\n\n\n<li><strong>Derived values:<\/strong> subtotal and total are calculated from items during render, not stored in separate state.<\/li>\n\n\n<li><strong>Props down, events up:<\/strong> <code>CartItemRow<\/code> gets an item and calls <code>onQuantityChange(id, qty)<\/code> and <code>onRemove(id)<\/code>.<\/li>\n\n\n<li><strong>Keys:<\/strong> use the cart item ID, never the index.<\/li>\n\n\n<li><strong>Empty, loading and error states:<\/strong> an empty cart message, skeleton rows while loading and a retry on error.<\/li>\n\n\n<li><strong>Accessibility:<\/strong> real buttons with labels like &#8220;Increase quantity of Notebook&#8221;, and announce total changes for screen readers.<\/li>\n\n\n<li><strong>Tests:<\/strong> test adding, removing and changing quantities with React Testing Library and MSW.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Hands-On React JS Interview Questions Practice<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers often ask you to build a small component live. Here is a counter that answers questions 30, 43 and 71.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useState } from \"react\";\n\n\/\/ Counter shows a number and buttons to change it.\nexport default function Counter() {\n  const [count, setCount] = useState(0); \/\/ count starts at 0\n\n  function addThree() {\n    \/\/ The updater form uses the latest value each time,\n    \/\/ so this adds 3, not 1.\n    setCount((current) =&gt; current + 1);\n    setCount((current) =&gt; current + 1);\n    setCount((current) =&gt; current + 1);\n  }\n\n  return (\n    &lt;div&gt;\n      &lt;p&gt;Count: {count}&lt;\/p&gt;\n      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Add 1&lt;\/button&gt;\n      &lt;button onClick={addThree}&gt;Add 3&lt;\/button&gt;\n      &lt;button onClick={() =&gt; setCount(0)}&gt;Reset&lt;\/button&gt;\n    &lt;\/div&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first button uses the current count directly, which is fine for one update. The Add 3 button uses the updater form, because React batches the three calls and each one gets the newest value. If you wrote setCount(count + 1) three times, the count would only go up by one.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next, here is a custom hook that fetches data safely. It answers questions 47, 56 and 65.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useEffect, useState } from \"react\";\n\n\/\/ useUser loads one user and ignores late responses.\nexport function useUser(userId) {\n  const [user, setUser] = useState(null);\n  const [error, setError] = useState(null);\n\n  useEffect(() =&gt; {\n    const controller = new AbortController(); \/\/ lets us cancel the request\n\n    fetch(`\/api\/users\/${userId}`, { signal: controller.signal })\n      .then((response) =&gt; {\n        if (!response.ok) throw new Error(\"Request failed\");\n        return response.json();\n      })\n      .then((data) =&gt; setUser(data))\n      .catch((err) =&gt; {\n        if (err.name !== \"AbortError\") setError(err); \/\/ ignore cancelled requests\n      });\n\n    \/\/ Cleanup runs before the next effect or when the component unmounts.\n    return () =&gt; controller.abort();\n  }, [userId]); \/\/ run again only when userId changes\n\n  return { user, error };\n}\n\n\/\/ UserCard uses the hook and shows loading, error or the user.\nexport function UserCard({ userId }) {\n  const { user, error } = useUser(userId);\n  if (error) return &lt;p&gt;Could not load user.&lt;\/p&gt;;\n  if (!user) return &lt;p&gt;Loading...&lt;\/p&gt;;\n  return &lt;h2&gt;{user.name}&lt;\/h2&gt;;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When userId changes quickly, the cleanup aborts the old request, so a slow old response can never replace newer data. The dependency array holds only userId, so the effect does not run on every render. In larger apps, a library such as TanStack Query adds caching and retries on top of this pattern.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in React JS Interview Questions<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Changing state directly:<\/strong> always create a new object or array, then call the setter.<\/li>\n\n\n<li><strong>Using the index as a key:<\/strong> use a stable ID from your data instead.<\/li>\n\n\n<li><strong>Missing effect dependencies:<\/strong> list every value the effect reads, or the effect uses stale data.<\/li>\n\n\n<li><strong>Overusing useMemo and useCallback:<\/strong> add them only when profiling shows a problem.<\/li>\n\n\n<li><strong>Storing derived data in state:<\/strong> compute it during render instead.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Answering React JS Interview Questions<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Explain the render cycle:<\/strong> state change, render, compare, commit, effects.<\/li>\n\n\n<li><strong>Write small components<\/strong> with one clear job each.<\/li>\n\n\n<li><strong>Mention modern tools,<\/strong> such as Vite or a framework, the React Compiler and React 19 Actions.<\/li>\n\n\n<li><strong>Talk about accessibility and testing<\/strong> in every component answer.<\/li>\n\n\n<li><strong>Use real examples,<\/strong> such as a slow list you fixed with virtualisation.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise these React JS interview questions, build a small todo app with Vite. It should add, complete and delete items, filter by status, and keep items after a page refresh. Hint: store the list in state, use the item ID as the key, and save to localStorage inside a useEffect.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/react.dev\/learn\">Quick Start in the React docs<\/a><\/li>\n\n\n<li><a href=\"https:\/\/react.dev\/reference\/rules\/rules-of-hooks\">Rules of Hooks<\/a><\/li>\n\n\n<li><a href=\"https:\/\/react.dev\/learn\/you-might-not-need-an-effect\">You Might Not Need an Effect<\/a><\/li>\n\n\n<li><a href=\"https:\/\/react.dev\/learn\/react-compiler\">React Compiler documentation<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>React JS interview questions focus on JSX, components, props, state, hooks and rendering.<\/li>\n\n\n<li>Props flow down and are read-only, while state belongs to a component and changes over time.<\/li>\n\n\n<li>Use stable keys, the updater form for state, and cleanup functions in effects.<\/li>\n\n\n<li>Reach for memoization only when needed, or let the React Compiler handle it.<\/li>\n\n\n<li>Know React 19 features such as Actions, use, and Server Components.<\/li>\n\n\n<li>Every one of the 110 questions now has a full answer, with code you can try.<\/li>\n\n\n<li>Practise building small components live, because coding rounds are common.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You now have question lists for Docker, Kubernetes, CI\/CD, AWS and React. Next, see the backend side of full-stack apps with the <a href=\"https:\/\/smitabharat.com\/blog\/go-rest-api-tutorial\/\">Go REST API tutorial<\/a>. For every topic in one place, browse the <a href=\"https:\/\/smitabharat.com\/blog\/go-interview-questions-hub\/\">Go interview questions hub<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>React JS interview questions show up in almost every frontend and full-stack interview, because React is still the most used library for building web&hellip;<\/p>\n","protected":false},"author":1,"featured_media":936,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[10],"tags":[132,77,126,133,131],"swapz_series":[],"class_list":["post-939","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-interview","tag-frontend","tag-intermediate","tag-interview-questions","tag-javascript","tag-react"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>React JS Interview Questions: Most Asked, Answered<\/title>\n<meta name=\"description\" content=\"React JS interview questions with full answers, basic to advanced: JSX, props, state, hooks, rendering, React 19, testing and real scenarios.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"React JS Interview Questions: Most Asked, Answered\" \/>\n<meta property=\"og:description\" content=\"React JS interview questions with full answers, basic to advanced: JSX, props, state, hooks, rendering, React 19, testing and real scenarios.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-12T03:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-10-24T18:51:08+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"67 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"React JS Interview Questions: 110 Most Asked, with Full Answers\",\"datePublished\":\"2026-10-12T03:30:00+00:00\",\"dateModified\":\"2026-10-24T18:51:08+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/\"},\"wordCount\":10399,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/react-js-interview-questions-featured.png\",\"keywords\":[\"Frontend\",\"Intermediate\",\"Interview Questions\",\"JavaScript\",\"React\"],\"articleSection\":[\"Interview\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/\",\"name\":\"React JS Interview Questions: Most Asked, Answered\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/react-js-interview-questions-featured.png\",\"datePublished\":\"2026-10-12T03:30:00+00:00\",\"dateModified\":\"2026-10-24T18:51:08+00:00\",\"description\":\"React JS interview questions with full answers, basic to advanced: JSX, props, state, hooks, rendering, React 19, testing and real scenarios.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/react-js-interview-questions-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/react-js-interview-questions-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"React JS Interview Questions featured image: topics from JSX to React 19\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/react-js-interview-questions\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"React JS Interview Questions: 110 Most Asked, with Full Answers\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"React JS Interview Questions: Most Asked, Answered","description":"React JS interview questions with full answers, basic to advanced: JSX, props, state, hooks, rendering, React 19, testing and real scenarios.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/","og_locale":"en_US","og_type":"article","og_title":"React JS Interview Questions: Most Asked, Answered","og_description":"React JS interview questions with full answers, basic to advanced: JSX, props, state, hooks, rendering, React 19, testing and real scenarios.","og_url":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-12T03:30:00+00:00","article_modified_time":"2026-10-24T18:51:08+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"67 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"React JS Interview Questions: 110 Most Asked, with Full Answers","datePublished":"2026-10-12T03:30:00+00:00","dateModified":"2026-10-24T18:51:08+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/"},"wordCount":10399,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-featured.png","keywords":["Frontend","Intermediate","Interview Questions","JavaScript","React"],"articleSection":["Interview"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/","url":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/","name":"React JS Interview Questions: Most Asked, Answered","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-featured.png","datePublished":"2026-10-12T03:30:00+00:00","dateModified":"2026-10-24T18:51:08+00:00","description":"React JS interview questions with full answers, basic to advanced: JSX, props, state, hooks, rendering, React 19, testing and real scenarios.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/react-js-interview-questions-featured.png","width":2400,"height":1260,"caption":"React JS Interview Questions featured image: topics from JSX to React 19"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/react-js-interview-questions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"React JS Interview Questions: 110 Most Asked, with Full Answers"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/939","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=939"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/939\/revisions"}],"predecessor-version":[{"id":981,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/939\/revisions\/981"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/936"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=939"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=939"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=939"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=939"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}