What is React?
React is an open-source front-end JavaScript library used for building user interfaces, specifically for single-page applications. It is component-based and declarative.
What is the history behind React's evolution?
It was created by Jordan Walke at Facebook, influenced by XHP. First deployed on Facebook's newsfeed in 2011 and open-sourced at JSConf US in May 2013.
What are the major features of React?
Key features include the Virtual DOM, JSX, Unidirectional Data Flow, Server-Side Rendering, and a component-based architecture.
What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like structures directly within JavaScript code.
What is the difference between an Element and a Component?
An Element is a plain object describing what you want to see on the screen. A Component is a function or class that accepts input (props) and returns elements.
How do you create components in React?
You can create components as JavaScript functions (Function Components) or by extending React.Component (Class Components).
When should you use a Class Component over a Function Component?
In modern React, Function Components with Hooks are preferred. Class components are generally only needed for Error Boundaries or legacy codebases.
What are Pure Components?
Components that only re-render if their props or state have changed (shallow comparison). React.PureComponent handles shouldComponentUpdate automatically.
What is state in React?
State is a built-in object that allows components to create and manage their own data. Unlike props, state is mutable and managed within the component.
What are props in React?
Props (short for properties) are read-only inputs passed from a parent component to a child component to configure it.
What is the difference between state and props?
Props are immutable and passed from parent to child. State is mutable and managed internally by the component itself.
What is the difference between HTML and React event handling?
React events use camelCase (e.g., onClick vs onclick), pass a function reference rather than a string, and cannot return false to prevent default behavior.
What are synthetic events in React?
React wraps native browser events in SyntheticEvent objects to ensure consistent behavior across different browsers.
What are inline conditional expressions?
These are expressions used inside JSX to render content conditionally, often using the logical AND operator (&&) or ternary operators.
What is the "key" prop and what is its benefit when used in arrays of elements?
A "key" is a unique string attribute for list items. It helps React identify which items have changed, been added, or removed, optimizing re-renders.
What is the Virtual DOM?
A lightweight JavaScript representation of the real DOM. React modifies this virtual copy and syncs changes to the real DOM (reconciliation).
How does the Virtual DOM work?
When state changes, React updates the Virtual DOM, compares it with the previous version (diffing), and efficiently updates only the changed parts of the real DOM.
What is the difference between Shadow DOM and Virtual DOM?
Shadow DOM is a browser technology for scoping CSS and variables (Web Components). Virtual DOM is a concept used by libraries like React on top of the browser APIs.
What is React Fiber?
Fiber is the reconciliation engine introduced in React 16. It allows splitting rendering work into chunks and prioritizing tasks (concurrency).
What is the main goal of React Fiber?
Its main goal is to enable incremental rendering and better performance for animations and gestures by pausing and resuming work.
What are controlled components?
Form components where the form data is handled by the React component's state rather than the internal DOM state.
What are uncontrolled components?
Form components where the form data is handled by the DOM itself. Values are accessed using Refs.
What is the difference between createElement and cloneElement?
createElement creates a new element from a type and props. cloneElement copies an existing element and merges new props into it.
What is Lifting State Up in React?
The process of moving state to a common ancestor component so that it can be shared between sibling components via props.
What are Higher-Order Components?
A pattern where a function takes a component and returns a new component, used for reusing component logic.
What is the children prop?
A special prop that allows you to pass components, text, or HTML elements as data to other components by nesting them inside the opening and closing tags.
How do you write comments in React?
Inside JSX, comments are written wrapped in curly braces: {/* This is a comment */}.
What is reconciliation?
The process through which React updates the DOM by diffing the Virtual DOM tree with the previous one to determine the most efficient updates.
Does the lazy function support named exports?
No, React.lazy currently supports default exports. You must re-export named exports as default in an intermediate module to use them.
Why does React use className instead of the class attribute?
class is a reserved keyword in JavaScript. Since JSX is transformed into JavaScript, className is used to define CSS classes.
What are Fragments?
Fragments (
Why are Fragments better than container divs?
They avoid DOM clutter, prevent invalid HTML (e.g., inside tables/lists), and reduce memory usage by not creating unnecessary nodes.
What are portals in React?
Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component (e.g., for modals).
What are stateless components?
Components that do not hold or manage state. They simply receive props and render UI.
What are stateful components?
Components that hold and manage local state, causing the component to re-render when that state changes.
How do you apply validation to props in React?
You can use the prop-types library to define the type and requirement (e.g., isRequired) of each prop passed to a component.
What are the advantages of React?
Fast rendering via Virtual DOM, reusable components, strong community, unidirectional data flow, and rich ecosystem (React Native, Next.js).
What are the limitations of React?
It is just a library (not a full framework), requires learning JSX, and the fast-paced ecosystem can lead to "churn" in best practices.
What are the recommended ways for static type checking?
TypeScript is the industry standard. Flow was used historically but has declined in popularity compared to TypeScript.
What is the use of the react-dom package?
It provides DOM-specific methods that can be used at the top level of your app to connect React components to the web page (e.g., render, hydrate).
What is ReactDOMServer?
A package that enables you to render components to static markup (HTML strings), primarily used for Server-Side Rendering (SSR).
How do you use innerHTML in React?
Use the dangerouslySetInnerHTML prop with an object containing a __html key. This acts as a warning about XSS risks.
How do you apply styles in React?
You can use CSS classes (className), inline styles (objects), CSS Modules, or CSS-in-JS libraries like Styled Components.
How are events different in React?
React events are synthetic (cross-browser wrappers), use camelCase naming, and are pooled (in older versions) for performance.
What is the impact of using indexes as keys?
It can cause performance issues and bugs with component state if the list order changes (sorting, filtering) or items are added/removed.
How do you conditionally render components?
Use if-else statements outside JSX, or ternary operators (cond ? A : B) and logical AND (cond && A) inside JSX.
Why we need to be careful when spreading props on DOM elements?
You might accidentally pass invalid HTML attributes to the DOM node or overwrite existing props with unwanted values.
How do you memoize a component?
Use React.memo() for function components to prevent re-renders if props haven't changed.
How do you implement Server-Side Rendering (SSR)?
Use ReactDOMServer.renderToString() on the server to generate HTML, send it to the client, and use hydrateRoot to attach event listeners.
How do you enable production mode in React?
Set the NODE_ENV environment variable to production during the build process (e.g., using Webpack or Vite).
Do Hooks replace render props and higher-order components?
Yes, in most cases Hooks provide a cleaner, less nested way to share logic, though the other patterns are still valid.
What is a switching component?
A component that renders one of many components based on a prop (e.g., a generic
What are React Mixins?
An obsolete way to share code between class components. They are deprecated and replaced by HOCs and Hooks.
What are the pointer events supported in React?
React supports standard pointer events like onPointerDown, onPointerMove, onPointerUp, onPointerEnter, etc.
Why should component names start with a capital letter?
React interprets lowercase tags as native HTML elements (like div) and capitalized tags as custom React components.
Are custom DOM attributes supported in React v16?
Yes, React 16+ allows custom attributes (including those without data- prefix), passing them through to the DOM.
How do you loop inside JSX?
You cannot use for loops directly. Use Array.prototype.map to iterate over data and return elements.
How do you access props within attribute quotes?
You don't use quotes. Use curly braces: .
What is a React PropType array with shape?
It defines an array of objects where the objects must match a specific schema: PropTypes.arrayOf(PropTypes.shape({...})).
How do you conditionally apply class attributes?
Use template literals or a utility library like clsx or classnames: className={`btn ${isActive ? 'active' : ''}`}.
What is the difference between React and ReactDOM?
React contains the core component logic. ReactDOM is the glue that renders that logic into the web browser DOM.
Why is ReactDOM separated from React?
To decouple the logic from the rendering target. React can be used with react-native, react-three-fiber, etc., not just the web.
How do you use the React label element?
Use htmlFor instead of the standard for attribute: .
How do you combine multiple inline style objects?
Use the spread operator or Object.assign: style={{ ...styleA, ...styleB }}.
How do you re-render the view when the browser is resized?
Add a resize event listener in useEffect (or componentDidMount) that updates a state variable holding the dimensions.
How do you pretty-print JSON with React?
Use the
tag:{JSON.stringify(data, null, 2)}.Why can't you update props in React?
Props are read-only (immutable) to ensure unidirectional data flow, making the application predictable and easier to debug.
How do you focus an input element on page load?
Use a ref and call ref.current.focus() inside a useEffect hook (or componentDidMount).
How can you find the version of React at runtime in the browser?
You can check React.version in the console or your code.
How do you add Google Analytics for React Router?
Listen to location changes via useLocation or history API and trigger a page view event to GA on route change.
How do you apply vendor prefixes to inline styles in React?
React does not automatically auto-prefix inline styles. You must add them manually or use a library to handle prefixing.
How do you import and export components using React and ES6?
Use export default Component or export const Component; import via import Component from './path'.
What are the exceptions to React component naming?
Component names must start with a capital letter. Hooks must start with "use".
Is it possible to use async/await in plain React?
Yes, inside lifecycle methods or useEffect, but the useEffect callback itself cannot be async (call an async function inside it).
What are common folder structures for React?
Grouping by file type (components, services), or grouping by feature/domain (e.g., UserProfile folder containing component, styles, and tests).
What are popular packages for animation?
Framer Motion, React Spring, and React Transition Group.
What are the benefits of style modules?
They automatically scope CSS to the component (generating unique class names), preventing style conflicts globally.
What are popular React-specific linters?
ESLint with eslint-plugin-react and eslint-plugin-react-hooks.
What is React Router?
A standard library for routing in React. It enables navigation among views/components and keeps the UI in sync with the URL.
How is React Router different from the history library?
React Router is a wrapper around the history library that provides React components and hooks for routing.
What are the components of React Router v6?
Key components include BrowserRouter, Routes, Route, Link, and NavLink.
What is the purpose of the push and replace methods of history?
push adds a new entry to the history stack (back button works). replace replaces the current entry (back button skips the replaced page).
How do you programmatically navigate using React Router v4?
Access history via props (HOC) or context and call history.push('/path').
How do you get query parameters in React Router v4?
Use this.props.location.search and parse it using URLSearchParams or a library like query-string.
Why do you get a "Router may have only one child element" warning?
In older versions,
could only wrap a single root child. You had to wrap children in a .How do you pass params to the history.push method in React Router v4?
history.push({ pathname: '/path', state: { detail: 'data' } }).
How do you implement a default or NotFound page?
Use a
} /> as the last route definition. How do you get history in React Router v4?
Use the withRouter HOC to inject history into component props.
How do you perform an automatic redirect after login?
Use the
component (v6) or history.push inside the login success callback. What is React Intl?
A library that provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations.
What are the main features of React Intl?
Formatting for numbers/dates, pluralization, and message translation support using standard ICU syntax.
What are the two ways of formatting in React Intl?
Using React components (e.g.,
) or the imperative API (e.g., intl.formatDate()). How do you use FormattedMessage as a placeholder with React Intl?
Use the defaultMessage prop or the description prop for context, usually within the defineMessages API.
How do you access the current locale with React Intl?
Use the useIntl hook or inject it via injectIntl HOC to access intl.locale.
How do you format a date using React Intl?
. What is the Shallow Renderer in React testing?
It renders a component one level deep without rendering child components, useful for unit testing in isolation.
What is the TestRenderer package in React?
It renders React components to pure JavaScript objects without a DOM, used for snapshot testing (e.g., with Jest).
What is the purpose of the ReactTestUtils package?
It provides utilities to manipulate rendered components and simulate events in a testing environment (often replaced by React Testing Library).
What is Jest?
A JavaScript testing framework created by Facebook, commonly used with React for its zero-config setup and snapshot testing.
What are the advantages of Jest over Jasmine?
Jest is faster (parallel testing), has built-in code coverage, snapshot testing, and requires less configuration.
Can you give a simple example of a Jest test case?
test('adds 1 + 2', () => { expect(1 + 2).toBe(3); });.
What is Flux?
An application architecture for React with unidirectional data flow (Actions -> Dispatcher -> Store -> View).
What is Redux?
A predictable state container for JS apps, inspired by Flux but using a single store and pure reducer functions.
What are the core principles of Redux?
Single source of truth (one store), State is read-only (emit actions), and Changes are made with pure functions (reducers).
What are the downsides of Redux compared to Flux?
Redux can have a steeper learning curve and more boilerplate code due to concepts like reducers and immutability.
What is the difference between mapStateToProps() and mapDispatchToProps()?
mapStateToProps connects Redux state to component props. mapDispatchToProps connects dispatch actions to component props.
Can you dispatch an action in a reducer?
No. Reducers must be pure functions without side effects. Dispatching causes a side effect and an infinite loop.
How do you access the Redux store outside a component?
You can export the store object from your setup file and import it directly to call store.getState() or store.dispatch().
What are the drawbacks of the MVW pattern?
It often leads to bidirectional data flow, making state changes hard to track and debug in complex apps.
Are there any similarities between Redux and RxJS?
Both deal with streams of data/events. Redux is like a single stream of state reductions; RxJS handles complex async streams.
How do you reset state in Redux?
Handle a specific RESET_APP action in your root reducer that returns undefined, causing child reducers to return initial state.
What is the difference between React Context and React Redux?
Context is built-in and good for low-frequency updates (themes). Redux provides devtools, middleware, and performance optimizations for frequent updates.
Why are Redux state functions called reducers?
Because they share the same signature as the callback function passed to Array.prototype.reduce ((accumulator, current) => newAccumulator).
How do you make an AJAX request in Redux?
Use middleware like redux-thunk or redux-saga to handle async logic and dispatch actions on success/failure.
Should you keep all component states in the Redux store?
No. Keep global data (user info, API cache) in Redux. Keep UI state (form inputs, modal open/close) in local component state.
What is the proper way to access the Redux store?
Use the useSelector hook in functional components or the connect HOC in class components.
What is the difference between a component and a container in React Redux?
Presentational components simply render props. Containers connect to Redux to fetch data and dispatch actions.
What is the purpose of constants in Redux?
They prevent typos in action type strings and allow easy refactoring/IDE support (export const ADD_TODO = 'ADD_TODO').
What are the different ways to write mapDispatchToProps()?
As a function (for custom logic) or as an object (shorthand where action creators are automatically wrapped in dispatch).
What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()?
It allows you to use the props passed to the wrapper component to influence the state selection or action dispatching logic.
How do you structure Redux top-level directories?
Common patterns include Rails-style (actions, constants, reducers folders) or Feature-based (user folder containing actions/reducer/components).
What is Redux Saga?
A middleware library that uses ES6 Generators to handle side effects (async calls) in a more readable and testable way.
What is the mental model of Redux Saga?
It acts like a separate thread in your application that is solely responsible for side effects.
What are the differences between call and put in Redux Saga?
call runs a function/promise and waits for it (blocking). put dispatches an action to the store (non-blocking).
What is Redux Thunk?
A middleware that allows action creators to return a function instead of an object, enabling async logic inside actions.
What are the differences between Redux Saga and Redux Thunk?
Thunks are simple and use functions/promises. Sagas are more powerful (cancellation, complex flows) but use Generators and are harder to learn.
What is Redux DevTools?
A browser extension that allows you to inspect every state change, time-travel (undo/redo actions), and view action payloads.
What are the features of Redux DevTools?
Time travel debugging, action logging, state diffing, and dispatching actions manually.
What are Redux selectors and why should you use them?
Functions that extract/derive data from the store. They encapsulate state structure and can be memoized (Reselect) for performance.
What is Redux Form?
A library to manage form state in Redux. (Note: It is largely deprecated in favor of React Final Form or Formik).
What are the main features of Redux Form?
Field validation, sync/async validation, submission handling, and persisting form state in the Redux store.
How do you add multiple middlewares to Redux?
Use applyMiddleware(thunk, logger, saga) inside the createStore (or configureStore) function.
How do you set the initial state in Redux?
Pass the initial state object as the second argument to createStore, or define default arguments in reducer functions.
How is Relay different from Redux?
Relay is specifically for fetching data from GraphQL APIs and managing that data. Redux is a generic state manager.
What is an action in Redux?
A plain JavaScript object with a type property (and optional payload) describing an event that happened.
What is the difference between React Native and React?
React renders HTML to the web DOM. React Native renders native UI components (View, Text) to iOS and Android platforms.
How do you test React Native apps?
Use Jest for unit tests, React Native Testing Library for component integration, and Detox/Appium for end-to-end testing.
How do you log in React Native?
console.log works and outputs to the Metro bundler terminal or the browser debugger/React Native Debugger.
How do you debug React Native apps?
Use the In-App Developer Menu, React Native Debugger (standalone app), or Flipper (platform debugging tool).
What is Reselect and how does it work?
A library for creating memoized selectors. It only re-calculates the result if the input arguments change, improving performance.
What is Flow?
A static type checker for JavaScript developed by Facebook, often used with React before TypeScript became dominant.
What is the difference between Flow and PropTypes?
Flow checks types at compile/build time (static). PropTypes checks types at runtime during development.
How do you use Font Awesome icons in React?
Use the react-fontawesome package to render icons as components, e.g.,
. What is React DevTools?
A browser extension to inspect the React component hierarchy, view props/state, and profile performance.
Why does DevTools not load in Chrome for local files?
Chrome restricts extensions on file:// protocol. You must enable "Allow access to file URLs" in extension settings or use a local server.
How do you use Polymer in React?
Polymer creates Web Components. React can render these custom elements just like standard HTML tags.
What are the advantages of React over Vue.js?
React has a larger ecosystem, better TypeScript support, and uses JSX (JavaScript power) vs Vue's template syntax.
What is the difference between React and Angular?
React is a library (View only) and flexible. Angular is a full-fledged MVC framework with built-in routing, HTTP, and forms.
Why is the React tab not showing up in DevTools?
It only appears if the website is running a development build of React. Production builds often disable inspection unless configured.
What are styled-components?
A CSS-in-JS library that allows you to write actual CSS code inside JavaScript files to style components using tagged template literals.
Can you give an example of styled-components?
const Button = styled.buttoncolor: red;; .
What is Relay?
A JavaScript framework for building data-driven React applications powered by GraphQL.
What are the main features of the Reselect library?
Memoization (caching results), composition (combining selectors), and efficient recalculation of derived data.
Can you give an example of Reselect usage?
createSelector([getUsers], users => users.filter(u => u.active)) returns a cached list until getUsers changes.
Can Redux only be used with React?
No, Redux is framework-agnostic and can be used with Angular, Vue, vanilla JS, or any other library.
Do you need a specific build tool to use Redux?
No, Redux is just JS. However, build tools are usually needed for the module system (ES6) used in most React/Redux apps.
How do Redux Form initial values get updated from state?
By passing an initialValues prop connected to the Redux state via mapStateToProps.
How do React PropTypes allow different types for one prop?
Use PropTypes.oneOfType([PropTypes.string, PropTypes.number]).
Can you import an SVG file as a React component?
Yes, using Create React App or SVGR, import { ReactComponent as Logo } from './logo.svg' works directly.
What is render hijacking in React?
A pattern (often in HOCs) where the wrapper controls whether and how the wrapped component is rendered.
How do you pass numbers to a React component?
Pass them inside curly braces:
. Do you need to keep all state in Redux? Should you ever use React's internal state?
No. Use Redux for global/shared data. Use React internal state for UI-specific, non-shared data (dropdown open, input hover).
What is the purpose of registerServiceWorker in React?
It was part of Create React App boilerplate to enable PWA features (offline caching) by registering a service worker.
What is the React.memo function?
A higher-order component that memoizes a functional component, skipping re-renders if props don't change.
What is the React.lazy function?
It allows you to render a dynamic import as a regular component, enabling code-splitting.
How do you prevent unnecessary updates using setState?
Check if the new value matches the current state before calling setState, or rely on React's automatic bailout for primitives.
How do you render arrays, strings, and numbers in React v16?
React 16+ can render arrays (returning a list), strings, and numbers directly from the return of a component.
What are Hooks?
Functions that let you "hook into" React state and lifecycle features from function components (e.g., useState, useEffect).
What rules must be followed for Hooks?
Only call Hooks at the top level (not inside loops/conditions) and only call them from React function components or custom Hooks.
How do you ensure Hooks follow the rules in your project?
Use the ESLint plugin eslint-plugin-react-hooks which enforces these rules automatically.
What are the differences between Flux and Redux?
Flux has multiple stores and a dispatcher. Redux has a single store and uses pure reducers instead of a dispatcher.
What are the benefits of React Router v4?
It introduced "Dynamic Routing," where routing takes place as your app is rendering, rather than in a static config configuration.
Can you describe the componentDidCatch lifecycle method signature?
componentDidCatch(error, info). It catches errors in child components and receives the error object and stack trace info.
In which scenarios do error boundaries not catch errors?
They do not catch errors in event handlers, asynchronous code, server-side rendering, or errors thrown in the boundary itself.
What is the behavior of uncaught errors in React v16?
Uncaught errors result in unmounting the entire component tree to prevent displaying corrupted UI.
What is the proper placement for error boundaries?
Place them at the top level to catch generic crashes, or wrap individual widgets to prevent one crash from breaking the whole app.
What is the benefit of a component stack trace from an error boundary?
It shows exactly where in the component tree the error happened, making debugging much easier than a generic JS stack trace.
What are default props?
A property on the component class (or using default parameters in functions) that sets fallback values if props are undefined.
What is the purpose of the displayName class property?
It sets the name of the component used in debugging messages and React DevTools.
What is the browser support for React applications?
React supports all modern browsers. Internet Explorer support was dropped in React 18.
What is code-splitting?
Splitting your bundle into smaller chunks that can be loaded on demand (lazy loading) to improve initial load time.
What are keyed Fragments?
Fragments that have a key attribute. Must use the explicit syntax
instead of <>. Does React support all HTML attributes?
Most, but they are camelCased (e.g., tabIndex). Some attributes like checked behave slightly differently (controlled vs default).
When do component props default to true?
If you pass a prop with no value, it defaults to true. E.g.,
is the same as . What is Next.js and what are its major features?
A framework for React offering Server-Side Rendering (SSR), Static Site Generation (SSG), file-system routing, and API routes.
How do you pass an event handler to a component?
Pass the function reference as a prop: .
How do you prevent a function from being called multiple times?
Use debouncing or throttling techniques, often with useCallback to maintain referential integrity.
How does JSX prevent injection attacks?
React escapes all variables embedded in JSX before rendering them, converting them to strings to prevent XSS.
How do you update rendered elements?
You don't update elements directly. You update state or props, and React creates new elements and updates the DOM.
How do you indicate that props are read-only?
Conceptually they always are. In TypeScript, you can explicitly type them as Readonly
. What are the conditions for safely using an index as a key?
The list must be static (no add/remove/reorder), and the items must have no internal ID or stable unique property.
Do keys need to be globally unique?
No, keys only need to be unique among siblings (within the same array).
What is the popular choice for form handling?
React Hook Form and Formik are the most popular libraries.
What are the advantages of Formik over the Redux Form library?
Formik is lighter, doesn't require Redux state (better performance), and is easier to set up.
Why are you not required to use inheritance?
React prefers composition over inheritance. You build complex UIs by combining small components, not extending classes.
Can you use web components in a React application?
Yes, React can render Web Components, though handling events and complex data passing sometimes requires manual mapping.
What is a dynamic import?
The import('./module') syntax that loads a module asynchronously, returning a Promise. Used for code splitting.
What are loadable components?
A library (@loadable/component) used for code splitting and server-side rendering, an alternative to React.lazy.
What is a Suspense component?
A component that lets you display a fallback (loading spinner) while children components are loading (e.g., via lazy load or data fetch).
What is route-based code splitting?
Loading code bundles only when the user navigates to a specific route, often implemented with React.lazy and Router.
What is the purpose of the default value in Context?
It is used only when a component subscribes to context but does not have a matching Provider above it in the tree.
What is the diffing algorithm?
React's heuristic algorithm to compare two trees (VDOM) and determine the minimum number of operations to transform one to the other.
What rules are covered by the diffing algorithm?
Different types of elements produce different trees; keys remain stable across renders; props changes update attributes.
When do you need to use refs?
For managing focus, text selection, triggering media playback, or integrating with third-party DOM libraries.
Must a prop be named "render" for render props?
No, any prop that is a function used to render UI is technically a render prop, often named render or children.
What are the problems with using render props with Pure Components?
If you create the render function inside the render method, it creates a new function reference every time, defeating shallow comparison.
What is the windowing technique?
Rendering only the small subset of rows in a large list that are currently visible in the viewport (Virtualization).
How do you print falsy values in JSX?
Convert them to strings: {String(false)} or {'' + value}. Booleans, null, and undefined do not render by default.
What is the typical use case for portals?
Modals, tooltips, and hovercards that need to visually "break out" of their parent container's CSS overflow.
How do you set a default value for an uncontrolled component?
Use the defaultValue attribute (or defaultChecked for checkboxes).
What is your favorite React stack?
(Opinion based) A common modern stack is: Next.js (Framework), Tailwind CSS (Styling), and React Query (Data Fetching).
What is the difference between the real DOM and the Virtual DOM?
Real DOM updates are slow and direct. Virtual DOM is a fast, in-memory representation used to compute minimal updates.
How do you add Bootstrap to a React application?
Install bootstrap npm package and import the CSS, or use a library like react-bootstrap for component-based usage.
Can you list the top websites or applications using React as a front-end framework?
Facebook, Instagram, Netflix, Airbnb, Uber, and WhatsApp Web.
Is it recommended to use the CSS-in-JS technique in React?
It is a valid choice (e.g., styled-components) for component-scoped styles, though CSS Modules and Tailwind are also popular.
Do you need to rewrite all class components with Hooks?
No. Hooks work side-by-side with classes. Rewrite only if you need to refactor or add new features.
How do you fetch data with React Hooks?
Use useEffect with an empty dependency array to fetch on mount, or use libraries like SWR or React Query.
Do Hooks cover all use cases for classes?
Almost all. The main exceptions were getSnapshotBeforeUpdate and componentDidCatch (Error Boundaries), though this is evolving.
What is the stable release for Hooks support?
Hooks were added in React 16.8.
Why do we use array destructuring (square bracket notation) in useState?
Because useState returns an array [value, setter]. Destructuring allows you to name these variables whatever you want.
What sources were used for introducing Hooks?
The React team introduced them at React Conf 2018 to solve code reuse and complexity issues in classes.
How do you access the imperative API of web components?
Use a ref attached to the web component custom element to call its methods directly.
What is Formik?
A popular library that helps with form state management, validation, and submission handling in React.
What are typical middleware choices for handling asynchronous calls in Redux?
Redux Thunk (simple, function based) and Redux Saga (complex, generator based).
Do browsers understand JSX code?
No. JSX must be transpiled into standard JavaScript (using Babel or SWC) before browsers can understand it.
Can you describe data flow in React?
It is unidirectional (top-down). Data flows from parent to child via props. Children communicate back via callbacks.
What is MobX?
A state management library that uses observable data and automatic reactions, offering a more mutable/OOP style than Redux.
What are the differences between Redux and MobX?
Redux is explicit, immutable, and uses boilerplate. MobX is implicit (magic), mutable, and requires less code.
Should you learn ES6 before learning ReactJS?
Yes. React relies heavily on ES6 features like classes, arrow functions, destructuring, and modules.
What is concurrent rendering?
A feature in React 18 that allows React to interrupt, pause, and resume rendering work to keep the UI responsive.
What is the difference between async mode and concurrent mode?
"Async mode" was an experimental name. It evolved into "Concurrent Mode" and is now simply "Concurrent features" in React 18.
Can you use JavaScript URLs in React v16.9?
Using URLs emits a warning in 16.9+ to prevent XSS attacks and is generally discouraged.
What is the purpose of the ESLint plugin for Hooks?
To enforce the Rules of Hooks (order of calls, dependencies array correctness) to prevent bugs.
What is the difference between imperative and declarative programming in React?
Imperative: Telling DOM how to change (jQuery). Declarative: Telling React what the UI should look like (React handles the how).
What are the benefits of using TypeScript with ReactJS?
Better intellisense, fewer runtime errors, self-documenting code, and safer refactoring of props and state.
How do you ensure a user remains authenticated on page refresh while using Context API state management?
Persist the auth token in localStorage or cookies and read it to initialize the Context state on app load.
What are the benefits of the new JSX transform?
It creates smaller bundle sizes and you no longer need to import React from 'react' in every file using JSX.
How is the new JSX transform different from the old transform?
Old: transformed
to React.createElement('div'). New: transforms to _jsx('div') imported from react/jsx-runtime.What are React Server Components?
Components that run exclusively on the server, sending zero bundle size to the client, allowing direct DB access.
What is prop drilling?
The process of passing data through many layers of components just to get it to a deeply nested child.
What is the difference between the useState and useRef Hooks?
useState triggers a re-render when updated. useRef persists values between renders but does not trigger re-renders.
What is a wrapper component?
A component that surrounds another component (or children) to provide styling, context, or logic (like an HOC or Layout).
What are the differences between the useEffect and useLayoutEffect Hooks?
useEffect runs asynchronously after paint. useLayoutEffect runs synchronously after DOM mutation but before paint (blocks visual update).
What are the differences between functional and class components?
Classes use this, render(), and lifecycle methods. Functions use Hooks and are just JS functions returning JSX.
What is Strict Mode in React?
A tool for highlighting potential problems in an application, like unsafe lifecycles or legacy API usage.
What is the benefit of Strict Mode?
It helps future-proof code by warning about deprecated features and detecting side effects by double-invoking functions.
Why does Strict Mode render twice in React?
In development, it intentionally double-invokes function components and lifecycles to help find side effects that shouldn't be there.
What are the rules of JSX?
Elements must be closed, adjacent elements must be wrapped in a parent, and class becomes className.
What is the reason multiple JSX tags must be wrapped?
JSX is syntactic sugar for function calls. A function can only return one value (one object), so siblings must be wrapped in one parent.
How do you prevent mutating array variables?
Use non-mutating methods like map, filter, concat, or the spread operator [...] instead of push or splice.
What are capture phase events?
Events that trickle down from the window to the target. In React, append Capture to the event name: onClickCapture.
How does React update the screen in an application?
Render phase (determine changes via VDOM diff) -> Commit phase (apply changes to DOM).
How does React batch multiple state updates?
It groups multiple setState calls into a single re-render to improve performance. React 18 batches practically all updates automatically.
Is it possible to prevent automatic batching?
Yes, using flushSync from react-dom forces an immediate re-render, opting out of batching (rarely needed).
What is React hydration?
The process of attaching React event listeners and state to existing HTML generated by Server-Side Rendering.
How do you update objects inside state?
Create a copy of the object with the changed property using spread syntax: setState({ ...obj, key: newValue }).
How do you update nested objects inside state?
You must deep copy or spread every level of nesting: setState({ ...obj, nested: { ...obj.nested, key: val } }).
How do you update arrays inside state?
Use spread syntax to create a new array: setArr([...oldArr, newItem]) or filter/map to remove/update items.
How do you use the Immer library for state updates?
Immer lets you write mutable logic (like draft.push(1)) producing an immutable state update under the hood.
What are the benefits of preventing direct state mutations?
It enables Time Travel debugging, helps React detect changes for re-rendering, and prevents subtle bugs.
What are the preferred and non-preferred array operations for updating state?
Preferred: map, filter, concat, slice, spread. Non-preferred (mutating): push, pop, shift, splice.
What will happen when defining nested function components?
The inner component will be redefined on every render, causing it to lose state and focus. Always define components at the top level.
Can I use keys for non-list items?
Yes, changing a key on a single component forces React to destroy and recreate it (resetting its state).
What are the guidelines to follow for writing reducers?
They must be pure functions, calculate new state based on arguments, and never mutate state directly.
What is useReducer hook? Can you describe its usage?
A hook for managing complex state logic using the (state, action) => newState pattern. Alternative to useState.
How do you compare useState and useReducer?
useState is best for simple values/independent state. useReducer is best for complex state logic or when next state depends on previous state.
How does Context work with the useContext hook?
const value = useContext(MyContext) lets you read the current context value from the nearest Provider without a wrapper component.
What are the use cases of the useContext hook?
Theming, User Authentication state, Localization/Translation, and sharing global settings.
When should you use client and server components?
Use Server Components for data fetching/backend access. Use Client Components (use client) for interactivity, state, and browser APIs.
What are the differences between the Page Router and App Router in Next.js?
Page Router uses the pages directory and is strictly client-focused with SSR methods. App Router uses app directory and defaults to React Server Components with layouts.
Why should we not update the state directly?
Directly updating state (e.g., this.state.val = 1) bypasses React's lifecycle and rendering mechanisms. React won't know the data has changed, so the component won't re-render to reflect the update.
What is the purpose of callback function as an argument of setState()?
The callback executes once the state has been updated and the component has re-rendered. It ensures that any logic running relies on the most current state and DOM.
How to bind methods or event handlers in JSX callbacks?
You can bind them in the constructor (this.method = this.method.bind(this)), use arrow functions in class properties (method = () => {}), or use inline arrow functions (though inline has performance implications).
How to pass a parameter to an event handler or callback?
Use an arrow function wrapper: onClick={() => this.handleClick(id)} or use the .bind method: onClick={this.handleClick.bind(this, id)}.
What is the use of refs?
Refs provide a way to access DOM nodes or React elements created in the render method directly. They are used for managing focus, text selection, media playback, or integrating with third-party DOM libraries.
How to create refs?
In Class components, use React.createRef() and attach it to an element via the ref attribute. In Function components, use the useRef() hook.
What are forward refs?
Ref forwarding is a technique for automatically passing a ref through a component to one of its children (usually a DOM node) using React.forwardRef((props, ref) => ....
Which is preferred option with in callback refs and findDOMNode()?
Callback refs are preferred. findDOMNode() is deprecated, impedes refactoring, and does not work in Strict Mode.
Why are String Refs legacy?
String refs (e.g., ref="myRef") are deprecated because they have performance issues, can't be composed easily, and fail in certain advanced scenarios (like library authors).
What are the different phases of component lifecycle?
The three main phases are Mounting (birth), Updating (growth/change), and Unmounting (death). There is also an Error Handling phase.
What are the lifecycle methods of React?
Common methods include constructor, render, componentDidMount, componentDidUpdate, and componentWillUnmount. Newer ones include getDerivedStateFromProps and getSnapshotBeforeUpdate.
How to create props proxy for HOC component?
Return a component that renders the wrapped component with the passed props and potentially new or modified props: return
. What is context?
Context provides a way to pass data through the component tree without having to pass props down manually at every level (solving "prop drilling").
What is the purpose of using super constructor with props argument?
It allows you to access this.props inside the constructor. If you don't pass props to super(), this.props will be undefined in the constructor (though available elsewhere).
How to set state with a dynamic key name?
Use ES6 computed property names (square brackets) inside the object passed to setState: this.setState({ [key]: value }).
What would be the common mistake of function being called every time the component renders?
Using immediate invocation syntax onClick={handleClick()} instead of passing the function reference onClick={handleClick}. This runs the function immediately during render.
What are error boundaries in React v16
Components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the whole app.
How are error boundaries handled in React v15?
React v15 didn't have error boundaries. If a JavaScript error occurred in the render or lifecycle methods, it would corrupt the internal state and often cause the entire app to unmount/crash.
What is the purpose of render method of react-dom?
ReactDOM.render() is the entry point used to mount the top-level React component into a specific DOM node (container) in the HTML page.
What will happen if you use setState in constructor?
It will likely throw a warning or error, and it won't trigger a re-render since the component hasn't mounted. You should initialize this.state directly instead.
Is it good to use setState() in componentWillMount() method?
No. It is deprecated. While it doesn't trigger an extra render, it is recommended to use the constructor for initialization or componentDidMount for side effects.
What will happen if you use props in initial state?
The state will be initialized with the prop value, but it won't update if the parent changes the prop later, leading to "source of truth" issues.
How you use decorators in React?
Decorators (like @connect) wrap a class component to add functionality. They require a transpiler (Babel) configuration as they are not yet standard JS syntax.
What is CRA and its benefits?
Create React App (CRA) is a CLI tool to set up a React environment. It handles Webpack, Babel, ESLint, and dev server configuration automatically, allowing "zero-config" development.
What is the lifecycle methods order in mounting?
constructor() -> getDerivedStateFromProps() -> render() -> componentDidMount().
What are the lifecycle methods going to be deprecated in React v16?
componentWillMount, componentWillReceiveProps, and componentWillUpdate are deprecated and flagged as "unsafe".
What is the purpose of getDerivedStateFromProps() lifecycle method?
It is a static method invoked right before rendering (both on mount and update). It enables a component to update its internal state as the result of changes in props.
What is the purpose of getSnapshotBeforeUpdate() lifecycle method?
It allows a component to capture some information from the DOM (e.g., scroll position) right before it is potentially changed, which is then passed to componentDidUpdate.
What is the recommended way for naming components?
Use PascalCase (UpperCamelCase) for component names (e.g., MyComponent, UserList). React treats components starting with lowercase as DOM tags.
What is the recommended ordering of methods in component class?
Static methods -> Constructor -> Lifecycle methods (Mounting then Updating) -> Custom methods (handlers) -> render.
Why we need to pass a function to setState()?
State updates may be asynchronous. Passing a function (prevState, props) => newState ensures you are calculating the new state based on the most up-to-date previous state.
Why is isMounted() an anti-pattern and what is the proper solution?
It checks if a component is still on screen, usually to suppress errors from async callbacks. The solution is to cancel the async task (subscription/promise) in componentWillUnmount.
What is the difference between constructor and getInitialState?
constructor is used for ES6 classes to initialize state. getInitialState was used in createReactClass (ES5) factories.
Can you force a component to re-render without calling setState?
Yes, by calling this.forceUpdate(). However, this bypasses shouldComponentUpdate and is generally discouraged.
What is the difference between super() and super(props) in React using ES6 classes?
super() executes the parent constructor. super(props) does the same but ensures this.props is available inside the constructor.
What is the difference between setState and replaceState methods?
setState merges the new state with the old one. replaceState (legacy/deprecated) throws out the current state and replaces it entirely with the new object.
How to listen to state changes?
Use the componentDidUpdate(prevProps, prevState) lifecycle method in classes or useEffect with the state variable in the dependency array in hooks.
What is the recommended approach of removing an array element in react state?
Use .filter() to create a new array without the unwanted element, then call setState. Do not use .splice() directly as it mutates the state.
Is it possible to use React without rendering HTML?
Yes. You can return null or false from render, or use React for non-DOM targets like React Native, Three.js (react-three-fiber), or PDF generation.
What are the possible ways of updating objects in state?
Use Object.assign({}, oldState, updates) or the ES6 spread operator setState({ ...oldState, ...updates }).
What are the approaches to include polyfills in your create-react-app?
Install react-app-polyfill and import it at the very top of your entry file (src/index.js) to support older browsers like IE11.
How to use https instead of http in create-react-app?
Set the HTTPS environment variable to true. You can run HTTPS=true npm start in the terminal.
How to avoid using relative path imports in create-react-app?
Configure a jsconfig.json (or tsconfig.json) file in the root with "compilerOptions": { "baseUrl": "src" } to support absolute imports.
How to update a component every second?
Set up a setInterval in componentDidMount that calls setState, and ensure you clear the interval in componentWillUnmount.
Why is a component constructor called only once?
The constructor is the initialization method for a class instance. React creates the instance once when mounting and reuses it for updates.
How to define constants in React?
Define them as const variables outside the component function/class, or as static properties inside a class.
How to programmatically trigger click event in React?
Create a ref for the element, attach it, and call this.myRef.current.click() in your event handler.
How to make AJAX call and In which component lifecycle methods should I make an AJAX call?
Use fetch or axios inside componentDidMount (classes) or useEffect (hooks) to ensure the data loads after the component exists.
What are render props?
A pattern where a component receives a function via a prop (often named render) and calls it to determine what to render, enabling logic reuse.
How to dispatch an action on load?
Call the action creator (mapped to props) inside componentDidMount or inside a useEffect hook with an empty dependency array.
How to use connect from React Redux?
Import connect, define mapStateToProps and mapDispatchToProps, and export the result: export default connect(mapState, mapDispatch)(MyComponent).
Whats the purpose of at symbol in the redux connect decorator?
It is the ES7 decorator syntax @connect(...) used to wrap the class component. It is syntactic sugar for higher-order component function calls.
How to use TypeScript in create-react-app application?
Run npx create-react-app my-app --template typescript, or add a tsconfig.json and install @types/react to an existing project.
Does the statics object work with ES6 classes in React?
No, statics was for createReactClass. In ES6 classes, you define static members using the static keyword inside the class body.
Why are inline ref callbacks or functions not recommended?
They create a new function instance on every render. If passed to a child, it may force the child to re-render, and callback refs get called twice (null then element).
What are HOC factory implementations?
A function that accepts a component and returns a new class component extending React.Component to add functionality.
How to use class field declarations syntax in React classes?
Define properties directly in the class body, e.g., handleClick = () => { ... }. This avoids manually binding methods in the constructor.
Why do you not need error boundaries for event handlers?
React does not catch errors inside event handlers. If an error occurs there, use a standard JavaScript try/catch block.
What is the difference between try catch block and error boundaries?
try/catch handles imperative, synchronous code (and async if awaited). Error Boundaries are declarative and handle errors in the declarative component tree (rendering/lifecycle).
What is the required method to be defined for a class component?
The render() method is the only mandatory method in a React class component.
What are the possible return types of render method?
React Elements (JSX), Arrays/Fragments, Portals, Strings/Numbers (text nodes), and Booleans/Null (render nothing).
What is the main purpose of constructor?
To initialize local state by assigning an object to this.state and to bind event handler methods to the instance.
Is it mandatory to define constructor for React component?
No. If you don't need to initialize state or bind methods (e.g., using class fields), you can omit the constructor.
Why should not call setState in componentWillUnmount?
Because the component is about to be removed from the DOM. A re-render will never happen, and it might cause memory leaks.
What is the purpose of getDerivedStateFromError?
It is a lifecycle method used in Error Boundaries to render a fallback UI after an error is thrown in a descendant component.
What is the methods order when component re-rendered?
getDerivedStateFromProps -> shouldComponentUpdate -> render -> getSnapshotBeforeUpdate -> componentDidUpdate.
What are the methods invoked during error handling?
static getDerivedStateFromError(error) and componentDidCatch(error, info).
What is the purpose of unmountComponentAtNode method?
It removes a mounted React component from the DOM and cleans up its event handlers and state. Used when React is manually mounted into a specific node.
What are the limitations with HOCs?
They can cause prop name collisions, require copying static methods, create "wrapper hell" in DevTools, and refs aren't passed through automatically.
How to debug forwardRefs in DevTools?
You can set the displayName property on the render function passed to forwardRef so it shows up clearly in the React DevTools component tree.
Is it good to use arrow functions in render methods?
It is generally discouraged because it creates a new function instance on every render, which can cause performance issues with pure child components.
How do you say that state updates are merged?
When you call setState, React merges the object you provide into the current state. It updates the keys you specified and leaves the others intact (shallow merge).
How do you pass arguments to an event handler?
Use an arrow function onClick={(e) => this.handle(id, e)} or the .bind method onClick={this.handle.bind(this, id)}.
How to prevent component from rendering?
Return false from shouldComponentUpdate, use React.memo (for functional components), or return null from the render method.
Give an example on How to use context?
Create context: const MyCtx = React.createContext(). Provide:
. Consume: useContext(MyCtx) or . How do you use contextType?
In a class component, set static contextType = MyContext. You can then access the context value via this.context.
What is a consumer?
A React component (
) that subscribes to context changes. It requires a function as a child to receive the current context value. How do you solve performance corner cases while using context?
Memoize the value object passed to the Provider (using useMemo or state) to prevent unnecessary re-renders of all consumers when the parent renders.
What is the purpose of forward ref in HOCs?
To ensure that if a user adds a ref to the wrapped component, the ref actually connects to the underlying wrapped component, not the HOC container.
Is it ref argument available for all functions or class components?
No. ref is not passed as a prop. It is only available as a second argument in functions wrapped with React.forwardRef.
Why do you need additional care for component libraries while using forward refs?
Because users of the library expect to be able to get a ref to the underlying DOM element for focus/animation, which requires explicit forwarding in custom components.
How to create react class components without ES6?
Use the create-react-class module, which provides a factory function createReactClass({ ... }).
Is it possible to use react without JSX?
Yes. You can use React.createElement(component, props, ...children) directly, though it is verbose and harder to read.
How do you create HOC using render props?
You can implement an HOC by creating a wrapper that renders a component with a render prop, essentially bridging the two patterns.
What is react scripts?
A package (part of Create React App) that contains the scripts and configuration for building, testing, and starting the React application.
What are the features of create react app?
Instant project structure, offline-first behavior (PWA), support for modern JS/CSS features, and a unified build pipeline without manual Webpack config.
What is the purpose of renderToNodeStream method?
It renders a React element to a Node.js Readable Stream. It allows sending HTML to the client in chunks (streaming), improving Time To First Byte (TTFB).
How do you get redux scaffolding using create-react-app?
Use the official Redux template: npx create-react-app my-app --template redux.
What is state mutation and how to prevent it?
State mutation is modifying the state object directly (this.state.x = 5). Prevent it by treating state as immutable, using setState, ...spread, or libraries like Immer.
