React Interview Master
Curated 200+ Questions to Crack Your Next Tech Interview
What is React?
BeginnerReact is a JavaScript library for building user interfaces, primarily for single-page applications. It's used for handling the view layer for web and ...
Full Answer:
React is a JavaScript library for building user interfaces, primarily for single-page applications. It's used for handling the view layer for web and mobile apps.
What is JSX?
BeginnerJSX stands for JavaScript XML. It allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() or appendChild(...
Full Answer:
JSX stands for JavaScript XML. It allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() or appendChild() methods.
What are the core features of React?
BeginnerCore features include Virtual DOM, JSX, Components, One-way data binding, and Simplicity (easy to learn and use).
Full Answer:
Core features include Virtual DOM, JSX, Components, One-way data binding, and Simplicity (easy to learn and use).
What is the Virtual DOM?
BeginnerVirtual DOM is a lightweight copy of the real DOM. React uses it to efficiently update the UI by comparing it with the previous version and only updat...
Full Answer:
Virtual DOM is a lightweight copy of the real DOM. React uses it to efficiently update the UI by comparing it with the previous version and only updating what changed.
What are Components in React?
BeginnerComponents are the building blocks of a React application. They are independent, reusable pieces of UI that can be functional or class-based.
Full Answer:
Components are the building blocks of a React application. They are independent, reusable pieces of UI that can be functional or class-based.
Difference between Functional and Class Components?
BeginnerFunctional components are simple functions returning JSX. Class components are ES6 classes. Functional components use Hooks for state, while Class com...
Full Answer:
Functional components are simple functions returning JSX. Class components are ES6 classes. Functional components use Hooks for state, while Class components use this.state.
What are Props?
BeginnerProps (properties) are read-only inputs passed from a parent component to a child component to communicate data.
Full Answer:
Props (properties) are read-only inputs passed from a parent component to a child component to communicate data.
What is State?
BeginnerState is an object that holds data that may change over the lifetime of a component. Unlike props, state is private and fully controlled by the compon...
Full Answer:
State is an object that holds data that may change over the lifetime of a component. Unlike props, state is private and fully controlled by the component.
What is the use of 'key' prop in lists?
BeginnerKeys help React identify which items have changed, been added, or removed. They should be unique among siblings to optimize rendering performance.
Full Answer:
Keys help React identify which items have changed, been added, or removed. They should be unique among siblings to optimize rendering performance.
What is useState hook?
BeginneruseState is a Hook that allows you to add React state to functional components. It returns the current state value and a function to update it.
Full Answer:
useState is a Hook that allows you to add React state to functional components. It returns the current state value and a function to update it.
What is useEffect hook?
BeginneruseEffect is used to perform side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.
Full Answer:
useEffect is used to perform side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.
Explain One-way Data Binding.
BeginnerIn React, data flows in one direction: from parent to child via props. This makes debugging and tracking data changes easier.
Full Answer:
In React, data flows in one direction: from parent to child via props. This makes debugging and tracking data changes easier.
What is a Single Page Application (SPA)?
BeginnerAn SPA is a web application that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server.
Full Answer:
An SPA is a web application that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server.
How do you handle events in React?
BeginnerEvents in React are named using camelCase (e.g., onClick) instead of lowercase. You pass a function as the event handler rather than a string.
Full Answer:
Events in React are named using camelCase (e.g., onClick) instead of lowercase. You pass a function as the event handler rather than a string.
What is Conditional Rendering?
BeginnerConditional rendering allows you to render different UI elements based on certain conditions using ternary operators, logical &&, or if-else statement...
Full Answer:
Conditional rendering allows you to render different UI elements based on certain conditions using ternary operators, logical &&, or if-else statements.
What is a React Fragment?
BeginnerFragments let you group a list of children without adding extra nodes to the DOM. It's written as <React.Fragment> or shorthand <>.</>
Full Answer:
Fragments let you group a list of children without adding extra nodes to the DOM. It's written as <React.Fragment> or shorthand <>.</>
What is 'create-react-app'?
BeginnerIt's a command-line tool that allows you to create a new React project with a pre-configured build setup.
Full Answer:
It's a command-line tool that allows you to create a new React project with a pre-configured build setup.
How do you add styles in React?
BeginnerStyles can be added via Inline CSS, CSS Stylesheets, CSS Modules, or CSS-in-JS libraries like Styled Components.
Full Answer:
Styles can be added via Inline CSS, CSS Stylesheets, CSS Modules, or CSS-in-JS libraries like Styled Components.
What is the 'children' prop?
BeginnerThe children prop allows you to pass components or elements as data to other components, enabling powerful composition patterns.
Full Answer:
The children prop allows you to pass components or elements as data to other components, enabling powerful composition patterns.
What is the significance of 'className'?
BeginnerSince 'class' is a reserved keyword in JavaScript, React uses 'className' to define CSS classes for HTML elements.
Full Answer:
Since 'class' is a reserved keyword in JavaScript, React uses 'className' to define CSS classes for HTML elements.
What are Hook rules?
BeginnerHooks must be called at the top level (not inside loops or conditions) and only from React functional components or custom hooks.
Full Answer:
Hooks must be called at the top level (not inside loops or conditions) and only from React functional components or custom hooks.
Difference between React and Angular?
BeginnerReact is a library (View only), uses Virtual DOM. Angular is a framework (Full MVC), uses Real DOM and two-way data binding.
Full Answer:
React is a library (View only), uses Virtual DOM. Angular is a framework (Full MVC), uses Real DOM and two-way data binding.
What is an event pooling?
BeginnerIn older React versions, event objects were reused for performance. Since React 17, event pooling has been removed.
Full Answer:
In older React versions, event objects were reused for performance. Since React 17, event pooling has been removed.
How to pass data from child to parent?
BeginnerPass a function as a prop from parent to child. The child calls this function with data as an argument.
Full Answer:
Pass a function as a prop from parent to child. The child calls this function with data as an argument.
What is the default port for React local server?
BeginnerThe default port is 3000.
Full Answer:
The default port is 3000.
What is the purpose of 'export default'?
BeginnerIt allows a file to export a single component or value as the default export, making it easier to import in other files.
Full Answer:
It allows a file to export a single component or value as the default export, making it easier to import in other files.
How to update state based on previous state?
BeginnerPass a callback function to the state setter: setState(prevState => prevState + 1).
Full Answer:
Pass a callback function to the state setter: setState(prevState => prevState + 1).
What is a Pure Component?
BeginnerA component that renders the same output for the same props and state. In class components, React.PureComponent handles shouldComponentUpdate automati...
Full Answer:
A component that renders the same output for the same props and state. In class components, React.PureComponent handles shouldComponentUpdate automatically.
What is the use of 'npm' in React?
BeginnerNPM (Node Package Manager) is used to install libraries, dependencies, and manage script execution in a React project.
Full Answer:
NPM (Node Package Manager) is used to install libraries, dependencies, and manage script execution in a React project.
What is 'strict mode' in React?
BeginnerStrictMode is a tool for highlighting potential problems in an application. It activates additional checks and warnings for its descendants.
Full Answer:
StrictMode is a tool for highlighting potential problems in an application. It activates additional checks and warnings for its descendants.
What is ReactDOM?
BeginnerReactDOM provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside the React model if you need...
Full Answer:
ReactDOM provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside the React model if you need to.
How to comment in JSX?
BeginnerUse curly braces with a block comment: {/* comment here */}.
Full Answer:
Use curly braces with a block comment: {/* comment here */}.
What are Synthetic Events?
BeginnerReact's cross-browser wrapper around the browser's native event, ensuring consistent behavior across different browsers.
Full Answer:
React's cross-browser wrapper around the browser's native event, ensuring consistent behavior across different browsers.
What is a Controlled Input?
BeginnerAn input whose value is driven by React state. Changes are handled by an onChange handler that updates the state.
Full Answer:
An input whose value is driven by React state. Changes are handled by an onChange handler that updates the state.
What is an Uncontrolled Input?
BeginnerAn input that maintains its own internal state. You access its value using a Ref instead of state.
Full Answer:
An input that maintains its own internal state. You access its value using a Ref instead of state.
What is the difference between HTML and React events?
BeginnerHTML events are strings (onclick='f()'), React events are functions (onClick={f}). React events use camelCase.
Full Answer:
HTML events are strings (onclick='f()'), React events are functions (onClick={f}). React events use camelCase.
What is Babel?
BeginnerBabel is a JavaScript compiler that converts modern JSX/ES6+ code into backwards-compatible JavaScript that older browsers can understand.
Full Answer:
Babel is a JavaScript compiler that converts modern JSX/ES6+ code into backwards-compatible JavaScript that older browsers can understand.
What is Webpack?
BeginnerWebpack is a module bundler that takes your assets (JS, CSS, images) and bundles them into small files for the browser.
Full Answer:
Webpack is a module bundler that takes your assets (JS, CSS, images) and bundles them into small files for the browser.
How to prevent a component from rendering?
BeginnerReturn 'null' from the component's render method or the functional component body.
Full Answer:
Return 'null' from the component's render method or the functional component body.
What is 'prop-types'?
BeginnerA library used for type-checking props. It helps catch bugs by ensuring components receive the correct data types.
Full Answer:
A library used for type-checking props. It helps catch bugs by ensuring components receive the correct data types.
Difference between UI and Logic?
BeginnerUI is what the user sees (JSX). Logic is how the data changes (State/Handlers). React separates these effectively.
Full Answer:
UI is what the user sees (JSX). Logic is how the data changes (State/Handlers). React separates these effectively.
What is a higher-order component (basic)?
BeginnerA pattern where a function takes a component and returns a new component with enhanced capabilities.
Full Answer:
A pattern where a function takes a component and returns a new component with enhanced capabilities.
What is the role of 'package.json'?
BeginnerIt lists project metadata, dependencies, and scripts required for the application.
Full Answer:
It lists project metadata, dependencies, and scripts required for the application.
How to handle forms in React?
BeginnerForms are typically handled as controlled components where state manages the inputs and handleSubmit processes the submission.
Full Answer:
Forms are typically handled as controlled components where state manages the inputs and handleSubmit processes the submission.
What is an Array Map in React?
BeginnerThe .map() function is the standard way to iterate over an array and return a list of JSX elements.
Full Answer:
The .map() function is the standard way to iterate over an array and return a list of JSX elements.
What is 'destructuring' in React?
BeginnerA JS feature often used in React to extract values from props or state objects into distinct variables.
Full Answer:
A JS feature often used in React to extract values from props or state objects into distinct variables.
What is React.memo()?
BeginnerA higher-order component that prevents a functional component from re-rendering if its props haven't changed.
Full Answer:
A higher-order component that prevents a functional component from re-rendering if its props haven't changed.
Importance of 'useEffect' dependency array?
BeginnerIt controls when the effect runs. Empty [] runs once, [prop] runs when prop changes, no array runs on every render.
Full Answer:
It controls when the effect runs. Empty [] runs once, [prop] runs when prop changes, no array runs on every render.
How to navigate between pages (basic)?
BeginnerUse a library like React Router with the <Link> component to navigate without refreshing the page.
Full Answer:
Use a library like React Router with the <Link> component to navigate without refreshing the page.
What is the 'public' folder for?
BeginnerIt contains static files like index.html, images, and manifest.json that don't go through the build process.
Full Answer:
It contains static files like index.html, images, and manifest.json that don't go through the build process.
Explain the Context API in detail.
ExperienceContext API provides a way to share values like themes or user info globally without prop drilling. It involves a Provider and a Consumer (or useConte...
Full Answer:
Context API provides a way to share values like themes or user info globally without prop drilling. It involves a Provider and a Consumer (or useContext hook).
When to use useMemo vs useCallback?
ExperienceuseMemo returns a memoized value (result of calculation). useCallback returns a memoized function (to prevent re-creation).
Full Answer:
useMemo returns a memoized value (result of calculation). useCallback returns a memoized function (to prevent re-creation).
How do you optimize React performance?
ExperienceUsing React.memo, useMemo, useCallback, lazy loading components with Suspense, and avoiding anonymous functions in props.
Full Answer:
Using React.memo, useMemo, useCallback, lazy loading components with Suspense, and avoiding anonymous functions in props.
What are React Portals?
ExperiencePortals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component (useful for modals).
Full Answer:
Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component (useful for modals).
Explain Error Boundaries.
ExperienceClass components that catch JS errors anywhere in their child component tree, log those errors, and display a fallback UI.
Full Answer:
Class components that catch JS errors anywhere in their child component tree, log those errors, and display a fallback UI.
How to handle global state without Redux?
ExperienceUse Context API combined with useReducer for complex logic, or simpler libraries like Zustand or Jotai.
Full Answer:
Use Context API combined with useReducer for complex logic, or simpler libraries like Zustand or Jotai.
What is useReducer hook?
ExperienceA hook for complex state logic. It's similar to Redux: takes a reducer (state, action) and returns the current state and a dispatch function.
Full Answer:
A hook for complex state logic. It's similar to Redux: takes a reducer (state, action) and returns the current state and a dispatch function.
Explain 'lifting state up'.
ExperienceMoving state to the closest common ancestor when several components need to reflect the same changing data.
Full Answer:
Moving state to the closest common ancestor when several components need to reflect the same changing data.
What are custom hooks?
ExperienceFunctions starting with 'use' that allow you to extract component logic into reusable functions that can still use other hooks.
Full Answer:
Functions starting with 'use' that allow you to extract component logic into reusable functions that can still use other hooks.
Difference between useMemo and React.memo?
ExperienceReact.memo is a HOC for components. useMemo is a hook for values within a component.
Full Answer:
React.memo is a HOC for components. useMemo is a hook for values within a component.
Explain forwardRef.
ExperienceA technique for automatically passing a ref through a component to one of its children.
Full Answer:
A technique for automatically passing a ref through a component to one of its children.
What is useRef and its common use cases?
ExperienceuseRef returns a mutable ref object. Used for accessing DOM elements directly or persisting values without triggering re-renders.
Full Answer:
useRef returns a mutable ref object. Used for accessing DOM elements directly or persisting values without triggering re-renders.
Explain React Router v6 features.
Experiencev6 introduced <Routes> instead of <Switch>, relative paths, useNavigate hook, and a simplified API for nested routes.
Full Answer:
v6 introduced <Routes> instead of <Switch>, relative paths, useNavigate hook, and a simplified API for nested routes.
How to fetch data in useEffect properly?
ExperienceDefine an async function inside useEffect, call it, and handle cleanups/aborts to prevent memory leaks.
Full Answer:
Define an async function inside useEffect, call it, and handle cleanups/aborts to prevent memory leaks.
What is the use of Layout components?
ExperienceTo wrap multiple pages in a consistent structure (Header, Footer, Sidebar) using the children prop.
Full Answer:
To wrap multiple pages in a consistent structure (Header, Footer, Sidebar) using the children prop.
How to implement Protected Routes?
ExperienceCreate a wrapper component that checks authentication state and redirects to login using <Navigate /> if not authenticated.
Full Answer:
Create a wrapper component that checks authentication state and redirects to login using <Navigate /> if not authenticated.
Difference between server-side and client-side routing?
ExperienceServer-side loads a new page from the server. Client-side updates the URL and changes the view without a full page reload.
Full Answer:
Server-side loads a new page from the server. Client-side updates the URL and changes the view without a full page reload.
How to use the useContext hook?
ExperienceAccepts a context object (from React.createContext) and returns the current context value for that context.
Full Answer:
Accepts a context object (from React.createContext) and returns the current context value for that context.
What is 'Prop Drilling' and how to avoid it?
ExperiencePassing data through many layers of components. Avoid it using Context API or state management libraries.
Full Answer:
Passing data through many layers of components. Avoid it using Context API or state management libraries.
Explain the concept of 'Render Props'.
ExperienceA technique for sharing code between components using a prop whose value is a function.
Full Answer:
A technique for sharing code between components using a prop whose value is a function.
What is the difference between useLayoutEffect and useEffect?
ExperienceuseEffect runs asynchronously after render. useLayoutEffect runs synchronously after all DOM mutations (before painting).
Full Answer:
useEffect runs asynchronously after render. useLayoutEffect runs synchronously after all DOM mutations (before painting).
How to optimize images in React?
ExperienceUse lazy loading, modern formats (WebP), responsive image sets, or frameworks like Next.js that handle it automatically.
Full Answer:
Use lazy loading, modern formats (WebP), responsive image sets, or frameworks like Next.js that handle it automatically.
What is Dependency Injection in React?
ExperiencePassing dependencies (like services or configurations) through props or Context to make components more testable and flexible.
Full Answer:
Passing dependencies (like services or configurations) through props or Context to make components more testable and flexible.
Explain React's 'Reconciliation'.
ExperienceThe algorithm React uses to diff one tree with another to determine which parts need to be changed.
Full Answer:
The algorithm React uses to diff one tree with another to determine which parts need to be changed.
How to debug React applications?
ExperienceUsing React DevTools, browser debugger statement, console logs, and profiling tools.
Full Answer:
Using React DevTools, browser debugger statement, console logs, and profiling tools.
What is the 'key' warning in console?
ExperienceOccurs when iterating over an array without providing a unique 'key' prop to the rendered elements.
Full Answer:
Occurs when iterating over an array without providing a unique 'key' prop to the rendered elements.
How to handle large forms in React?
ExperienceUse libraries like Formik or React Hook Form to manage validation, state, and complex submission logic efficiently.
Full Answer:
Use libraries like Formik or React Hook Form to manage validation, state, and complex submission logic efficiently.
What is the Virtual DOM's 'Diffing' algorithm?
ExperienceReact compares two versions of the virtual DOM. It assumes different types produce different trees and uses keys for list comparisons.
Full Answer:
React compares two versions of the virtual DOM. It assumes different types produce different trees and uses keys for list comparisons.
Explain state persistence (localStorage) in React.
ExperienceInitialize state from localStorage and use useEffect to sync state changes back to localStorage.
Full Answer:
Initialize state from localStorage and use useEffect to sync state changes back to localStorage.
What are Higher-Order Components (HOC) examples?
ExperiencewithAuth (auth checks), connect (Redux), withRouter (legacy routing), or custom withLogger.
Full Answer:
withAuth (auth checks), connect (Redux), withRouter (legacy routing), or custom withLogger.
How to handle API errors globally?
ExperienceUsing Axios interceptors or a custom wrapper around the fetch API to catch 401/500 errors centrally.
Full Answer:
Using Axios interceptors or a custom wrapper around the fetch API to catch 401/500 errors centrally.
Difference between Shadow DOM and Virtual DOM?
ExperienceShadow DOM is a browser technology for scoping styles. Virtual DOM is a JavaScript concept for efficient UI updates.
Full Answer:
Shadow DOM is a browser technology for scoping styles. Virtual DOM is a JavaScript concept for efficient UI updates.
What is React.lazy and Suspense?
Experiencelazy allows you to render a dynamic import as a regular component. Suspense lets you show a fallback UI while it's loading.
Full Answer:
lazy allows you to render a dynamic import as a regular component. Suspense lets you show a fallback UI while it's loading.
What are fragments shorthand issues?
ExperienceThe <> shorthand doesn't support the 'key' attribute. For lists, you must use <React.Fragment key={id}>.
Full Answer:
The <> shorthand doesn't support the 'key' attribute. For lists, you must use <React.Fragment key={id}>.
How to use useImperativeHandle?
ExperienceCustomizes the instance value that is exposed to parent components when using refs.
Full Answer:
Customizes the instance value that is exposed to parent components when using refs.
What is the importance of 'cleanup function' in useEffect?
ExperiencePrevents memory leaks by clearing timers, unsubscribing from sockets, or cancelling fetch requests when a component unmounts.
Full Answer:
Prevents memory leaks by clearing timers, unsubscribing from sockets, or cancelling fetch requests when a component unmounts.
How to fetch data derived from multiple state changes?
ExperienceInclude all relevant state variables in the useEffect dependency array.
Full Answer:
Include all relevant state variables in the useEffect dependency array.
Explain component composition vs inheritance.
ExperienceReact recommends composition (using children or props) over inheritance to reuse code between components.
Full Answer:
React recommends composition (using children or props) over inheritance to reuse code between components.
What is the 'batching' of updates?
ExperienceReact groups multiple state updates into a single re-render for better performance (Automatic Batching in React 18).
Full Answer:
React groups multiple state updates into a single re-render for better performance (Automatic Batching in React 18).
How to test components thoroughly?
ExperienceFocus on user behavior using React Testing Library (RTL) and Jest for unit and integration tests.
Full Answer:
Focus on user behavior using React Testing Library (RTL) and Jest for unit and integration tests.
What is 'shallow rendering' in tests?
ExperienceTesting a component in isolation without rendering its children (mostly used with Enzyme, less common now).
Full Answer:
Testing a component in isolation without rendering its children (mostly used with Enzyme, less common now).
How to handle accessibility (A11y) in React?
ExperienceUse semantic HTML, aria-* attributes, and tools like eslint-plugin-jsx-a11y to ensure accessibility.
Full Answer:
Use semantic HTML, aria-* attributes, and tools like eslint-plugin-jsx-a11y to ensure accessibility.
What is 'Hydration' in React?
ExperienceThe process where React attaches event listeners to HTML that was pre-rendered on the server.
Full Answer:
The process where React attaches event listeners to HTML that was pre-rendered on the server.
How to manage theme (Dark/Light) in React?
ExperienceUse Context API to provide a 'theme' string and CSS variables or a library like styled-components' ThemeProvider.
Full Answer:
Use Context API to provide a 'theme' string and CSS variables or a library like styled-components' ThemeProvider.
What is the use of 'debugger;' statement?
ExperienceIt pauses execution and opens the browser's debugger if available, allowing for step-by-step code inspection.
Full Answer:
It pauses execution and opens the browser's debugger if available, allowing for step-by-step code inspection.
How to fix 'Maximum update depth exceeded' error?
ExperienceCheck for infinite loops in useEffect (by adding/fixing dependencies) or event handlers updating state unconditionally.
Full Answer:
Check for infinite loops in useEffect (by adding/fixing dependencies) or event handlers updating state unconditionally.
Explain the 'module' pattern in React project structure.
ExperienceGrouping related components, hooks, and services into feature-based folders instead of just 'components' or 'hooks'.
Full Answer:
Grouping related components, hooks, and services into feature-based folders instead of just 'components' or 'hooks'.
How to use 'URL Search Params' in React?
ExperienceUsing useSearchParams hook from react-router-dom to read and update query strings.
Full Answer:
Using useSearchParams hook from react-router-dom to read and update query strings.
What is React's Concurrent Mode?
ExperienceA set of new features that help React apps stay responsive and gracefully adjust to the user's device capabilities.
Full Answer:
A set of new features that help React apps stay responsive and gracefully adjust to the user's device capabilities.
How to use SVGs effectively in React?
ExperienceImport them as components (@svgr/webpack) or use them in <img> tags or as inline JSX for styling flexibility.
Full Answer:
Import them as components (@svgr/webpack) or use them in <img> tags or as inline JSX for styling flexibility.
What is the React Fiber architecture?
AdvancedFiber is the current reconciliation engine. It allows React to pause, prioritize, and reuse work, enabling features like Concurrent Rendering.
Full Answer:
Fiber is the current reconciliation engine. It allows React to pause, prioritize, and reuse work, enabling features like Concurrent Rendering.
Explain SSR, SSG, and ISR in Next.js.
AdvancedSSR: Server-Side Rendering (per request). SSG: Static Site Generation (build time). ISR: Incremental Static Regeneration (background update).
Full Answer:
SSR: Server-Side Rendering (per request). SSG: Static Site Generation (build time). ISR: Incremental Static Regeneration (background update).
How do you implement Micro-frontends with React?
AdvancedUsing Module Federation (Webpack 5), iframes, or custom mounting logic to combine independent apps.
Full Answer:
Using Module Federation (Webpack 5), iframes, or custom mounting logic to combine independent apps.
Explain the 'useTransition' hook.
AdvancedAllows you to mark state updates as non-urgent transitions, keeping the UI responsive while heavy updates happen in background.
Full Answer:
Allows you to mark state updates as non-urgent transitions, keeping the UI responsive while heavy updates happen in background.
What is the 'useDeferredValue' hook?
AdvancedLets you defer re-rendering a non-urgent part of the tree until the urgent parts have finished updating.
Full Answer:
Lets you defer re-rendering a non-urgent part of the tree until the urgent parts have finished updating.
How to handle memory leaks in large applications?
AdvancedProperly unsubscribing in useEffect, avoiding closures on old state, and profiling the application using browser memory tools.
Full Answer:
Properly unsubscribing in useEffect, avoiding closures on old state, and profiling the application using browser memory tools.
Deep dive: Reconciliation and Diffing logic.
AdvancedReact uses O(n) complexity by assuming stable keys and focusing on element type changes to efficiently update the tree.
Full Answer:
React uses O(n) complexity by assuming stable keys and focusing on element type changes to efficiently update the tree.
Redux Saga vs Redux Thunk.
AdvancedThunk uses function-based middleware for simple async. Saga uses Generators for complex side-effect management and testing.
Full Answer:
Thunk uses function-based middleware for simple async. Saga uses Generators for complex side-effect management and testing.
Explain Server Components in React 18.
AdvancedComponents that run only on the server, sending zero JavaScript to the client while still being interactive through client islands.
Full Answer:
Components that run only on the server, sending zero JavaScript to the client while still being interactive through client islands.
What is 'Atomic State Management' (Recoil/Jotai)?
AdvancedManaging state as small, independent 'atoms' that can be composed, avoiding the monolithic store approach of Redux.
Full Answer:
Managing state as small, independent 'atoms' that can be composed, avoiding the monolithic store approach of Redux.
How to implement Custom Middleware in Redux?
AdvancedA triple-curried function: (store) => (next) => (action) => { ... next(action); }.
Full Answer:
A triple-curried function: (store) => (next) => (action) => { ... next(action); }.
Web Workers integration with React.
AdvancedOffloading heavy computations to a separate thread to prevent blocking the UI thread (main thread).
Full Answer:
Offloading heavy computations to a separate thread to prevent blocking the UI thread (main thread).
Security best practices: XSS and Data Sanitization.
AdvancedDon't use dangerouslySetInnerHTML unless necessary, use sanitization libraries (DOMPurify), and leverage modern CSP headers.
Full Answer:
Don't use dangerouslySetInnerHTML unless necessary, use sanitization libraries (DOMPurify), and leverage modern CSP headers.
Explain the 'Double Invoke' in StrictMode.
AdvancedReact 18 intentionally remounts components in dev mode to help developers find bugs related to side effects and cleanups.
Full Answer:
React 18 intentionally remounts components in dev mode to help developers find bugs related to side effects and cleanups.
What is 'Zustand' and why is it popular?
AdvancedA small, fast state-management library based on hooks. It has zero boilerplate compared to Redux.
Full Answer:
A small, fast state-management library based on hooks. It has zero boilerplate compared to Redux.
Optimizing Web Vitals in a React app.
AdvancedFocusing on LCP (Lazy loading), FID (Transitions), and CLS (Fixed aspect ratios for media).
Full Answer:
Focusing on LCP (Lazy loading), FID (Transitions), and CLS (Fixed aspect ratios for media).
Explain 'Code Splitting' beyond React.lazy.
AdvancedSplitting vendor code, route-based splitting, and dynamic imports for specific libraries only when needed.
Full Answer:
Splitting vendor code, route-based splitting, and dynamic imports for specific libraries only when needed.
How does the 'useSyncExternalStore' hook work?
AdvancedAllows libraries to subscribe to external data stores in a way that's compatible with concurrent rendering.
Full Answer:
Allows libraries to subscribe to external data stores in a way that's compatible with concurrent rendering.
Using 'useId' for unique identifiers.
AdvancedGenerates unique IDs stable across server and client, primarily for accessibility attributes.
Full Answer:
Generates unique IDs stable across server and client, primarily for accessibility attributes.
Explain 'Automatic Batching' in React 18.
AdvancedReact now batches state updates from promises, setTimeout, and native events, not just React events.
Full Answer:
React now batches state updates from promises, setTimeout, and native events, not just React events.
What is 'Tree Shaking'?
AdvancedRemoving unused code from the final bundle during the build process to minimize file size.
Full Answer:
Removing unused code from the final bundle during the build process to minimize file size.
Implementing complex animations (e.g., Framer Motion).
AdvancedUsing layout animations, variants, and AnimatePresence for entering/exiting shared layouts.
Full Answer:
Using layout animations, variants, and AnimatePresence for entering/exiting shared layouts.
Testing Hooks with renderHook.
AdvancedUsing @testing-library/react-hooks to test custom hooks in isolation without a component.
Full Answer:
Using @testing-library/react-hooks to test custom hooks in isolation without a component.
How to handle 'Hydration Mismatch'?
AdvancedEnsure server and client render identical content. Use useEffect for client-only logic or suppress warnings.
Full Answer:
Ensure server and client render identical content. Use useEffect for client-only logic or suppress warnings.
Explain 'Streaming SSR'.
AdvancedSending HTML chunks to the client as they are ready, allowing parts of the page to show up before everything is loaded.
Full Answer:
Sending HTML chunks to the client as they are ready, allowing parts of the page to show up before everything is loaded.
What are 'Ref' utility patterns (e.g., Callback Refs)?
AdvancedUsing a function instead of a ref object to run code whenever the DOM node is set or unset.
Full Answer:
Using a function instead of a ref object to run code whenever the DOM node is set or unset.
Architecture: Feature-Slicing Design (FSD).
AdvancedA modern architectural pattern for splitting frontend apps into layers like features, entities, and shared.
Full Answer:
A modern architectural pattern for splitting frontend apps into layers like features, entities, and shared.
How to implement Multi-language (i18n) at scale?
AdvancedUsing react-i18next with lazy-loaded translation files and SEO-friendly routing.
Full Answer:
Using react-i18next with lazy-loaded translation files and SEO-friendly routing.
Security: JWT storage (Cookie vs LocalStorage).
AdvancedCookies (httpOnly) are safer from XSS; LocalStorage is easier but vulnerable to script injection.
Full Answer:
Cookies (httpOnly) are safer from XSS; LocalStorage is easier but vulnerable to script injection.
Explain 'Module Federation' in depth.
AdvancedA Webpack 5 feature allowing a JavaScript application to dynamically load code from another application at runtime.
Full Answer:
A Webpack 5 feature allowing a JavaScript application to dynamically load code from another application at runtime.
Performance: Virtualization (react-window).
AdvancedRendering only the visible portion of a large list to save memory and DOM nodes.
Full Answer:
Rendering only the visible portion of a large list to save memory and DOM nodes.
What is 'useInsertionEffect'?
AdvancedA hook for CSS-in-JS libraries to inject styles before other effects run, avoiding reflows.
Full Answer:
A hook for CSS-in-JS libraries to inject styles before other effects run, avoiding reflows.
How to build a Design System with React?
AdvancedCreating a library of atomic components, documented with Storybook, and shared via NPM.
Full Answer:
Creating a library of atomic components, documented with Storybook, and shared via NPM.
Handling Cross-tab Communication.
AdvancedUsing BroadcastChannel API, localStorage events, or Shared Workers.
Full Answer:
Using BroadcastChannel API, localStorage events, or Shared Workers.
Explain 'Command Pattern' in React.
AdvancedDecoupling the requester of an action from the object that performs the action (useful for undo/redo).
Full Answer:
Decoupling the requester of an action from the object that performs the action (useful for undo/redo).
What is 'Preact' and when to use it?
AdvancedA 3kb alternative to React with the same API. Use it for extreme performance or size constraints.
Full Answer:
A 3kb alternative to React with the same API. Use it for extreme performance or size constraints.
What is 'TanStack Query' (React Query)?
AdvancedA powerful library for data fetching, caching, and state synchronization with the server.
Full Answer:
A powerful library for data fetching, caching, and state synchronization with the server.
Explain 'Finite State Machines' with XState.
AdvancedModeling complex UI states as mathematical state machines to prevent impossible states.
Full Answer:
Modeling complex UI states as mathematical state machines to prevent impossible states.
Advanced usage of useReducer with Middleware.
AdvancedWrapping dispatch to add logging or async handle capabilities to useReducer.
Full Answer:
Wrapping dispatch to add logging or async handle capabilities to useReducer.
How to scale React applications for millions of users?
AdvancedCDN caching, Micro-frontends, robust CI/CD, and highly optimized bundle sizes.
Full Answer:
CDN caching, Micro-frontends, robust CI/CD, and highly optimized bundle sizes.
What are 'React Native' differences?
AdvancedUses native components instead of web elements. No CSS, uses StyleSheet. No DOM, uses Yoga engine for layout.
Full Answer:
Uses native components instead of web elements. No CSS, uses StyleSheet. No DOM, uses Yoga engine for layout.
Explain 'Reflecting' state to URL.
AdvancedKeeping filters and search terms in the URL query string so the page state is shareable.
Full Answer:
Keeping filters and search terms in the URL query string so the page state is shareable.
How to optimize Context API re-renders?
AdvancedSplitting context into smaller ones or using a selector-like pattern with children memoization.
Full Answer:
Splitting context into smaller ones or using a selector-like pattern with children memoization.
What is 'Experimental React' branch?
AdvancedFeatures likely to land in future versions (like previously with Hooks and Concurrent Mode).
Full Answer:
Features likely to land in future versions (like previously with Hooks and Concurrent Mode).
Handling File Uploads at scale.
AdvancedUsing multipart uploads, progress tracking, and secure presigned URLs for cloud storage.
Full Answer:
Using multipart uploads, progress tracking, and secure presigned URLs for cloud storage.
What is 'Isomorphic JavaScript'?
AdvancedJavaScript code that can run on both the client and the server.
Full Answer:
JavaScript code that can run on both the client and the server.
Explain 'Duck Pattern' in Redux.
AdvancedCombining actions, reducers, and action types into a single file to reduce file scattering.
Full Answer:
Combining actions, reducers, and action types into a single file to reduce file scattering.
Using 'Proxy' for state management.
AdvancedThe foundation of libraries like Valtio or MobX to track changes automatically without explicit setters.
Full Answer:
The foundation of libraries like Valtio or MobX to track changes automatically without explicit setters.
What is 'Shadowing' in Gatsby/Next.js?
AdvancedCustomizing a theme or library by providing a file at a specific path that takes precedence.
Full Answer:
Customizing a theme or library by providing a file at a specific path that takes precedence.
Future of React: What's after React 18/19?
AdvancedReact Forget (Compiler), native-like transitions, and move towards even more server-driven architectures.
Full Answer:
React Forget (Compiler), native-like transitions, and move towards even more server-driven architectures.
How to implement a useLocalStorage hook?
ExperienceCreate a hook that takes a key and initial value. Use useState initialized with a function that reads from localStorage, and a useEffect that writes t...
Full Answer:
Create a hook that takes a key and initial value. Use useState initialized with a function that reads from localStorage, and a useEffect that writes to localStorage whenever state changes.
Code Example:
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key);
return saved ? JSON.parse(saved) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}Reverse a string in JavaScript without built-in 'reverse'?
BeginnerUse a decrementing loop or reduce.
Full Answer:
Use a decrementing loop or reduce.
Code Example:
const reverseStr = str => [...str].reduce((acc, char) => char + acc, '');Implement a simple counter with useReducer.
BeginnerDefine a reducer function with 'increment' and 'decrement' actions.
Full Answer:
Define a reducer function with 'increment' and 'decrement' actions.
Code Example:
const reducer = (state, action) => {
switch(action.type) {
case 'inc': return { count: state.count + 1 };
case 'dec': return { count: state.count - 1 };
default: return state;
}
};How to debounce a function in React?
ExperienceUse a combination of useEffect and setTimeout to delay execution until the user stops typing.
Full Answer:
Use a combination of useEffect and setTimeout to delay execution until the user stops typing.
Code Example:
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(searchTerm);
}, 500);
return () => clearTimeout(timer);
}, [searchTerm]);Find the longest word in a sentence.
BeginnerSplit the sentence into an array of words and use 'reduce' to find the one with the maximum length.
Full Answer:
Split the sentence into an array of words and use 'reduce' to find the one with the maximum length.
Code Example:
const findLongest = str => str.split(' ').reduce((a, b) => b.length > a.length ? b : a);Remove duplicates from an array.
BeginnerUse a Set for a clean, efficient solution.
Full Answer:
Use a Set for a clean, efficient solution.
Code Example:
const unique = arr => [...new Set(arr)];Implement a deep clone function.
AdvancedFor simple objects, use JSON.parse(JSON.stringify(obj)). For complex ones involving recursive functions, handle them manually or use Lodash.
Full Answer:
For simple objects, use JSON.parse(JSON.stringify(obj)). For complex ones involving recursive functions, handle them manually or use Lodash.
Code Example:
const deepClone = obj => JSON.parse(JSON.stringify(obj));Check if a string is a palindrome.
BeginnerCompare the string with its reversed version.
Full Answer:
Compare the string with its reversed version.
Code Example:
const isPalindrome = str => str === [...str].reverse().join('');Convert a nested object to a flat URL query string.
AdvancedRecursively iterate through keys and values.
Full Answer:
Recursively iterate through keys and values.
Code Example:
const flatten = obj => Object.entries(obj).map(([k, v]) => `${k}=${v}`).join('&');Flatten a nested array.
ExperienceUse the built-in .flat(Infinity) or a recursive function.
Full Answer:
Use the built-in .flat(Infinity) or a recursive function.
Code Example:
const flatArray = arr => arr.flat(Infinity);Count character occurrences in a string.
BeginnerIterate through the string and build a frequency map.
Full Answer:
Iterate through the string and build a frequency map.
Code Example:
const countChars = str => [...str].reduce((acc, c) => ({ ...acc, [c]: (acc[c] || 0) + 1 }), {});Group an array of objects by a property.
ExperienceUse reduce to build an object where keys are the property values.
Full Answer:
Use reduce to build an object where keys are the property values.
Code Example:
const groupBy = (arr, prop) => arr.reduce((acc, obj) => {
const key = obj[prop];
if (!acc[key]) acc[key] = [];
acc[key].push(obj);
return acc;
}, {});Implement a basic Fetch with error handling.
BeginnerUse async/await with try/catch and check response.ok.
Full Answer:
Use async/await with try/catch and check response.ok.
Code Example:
async function getData(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error('Error');
return await res.json();
} catch (err) { console.error(err); }
}Create a simple Toggle hook.
BeginnerA hook that returns a boolean state and a function to flip it.
Full Answer:
A hook that returns a boolean state and a function to flip it.
Code Example:
function useToggle(initial = false) {
const [s, setS] = useState(initial);
const toggle = () => setS(!s);
return [s, toggle];
}Find the intersection of two arrays.
BeginnerFilter one array based on the presence of elements in the other.
Full Answer:
Filter one array based on the presence of elements in the other.
Code Example:
const intersect = (a, b) => a.filter(v => b.includes(v));Sum of all numbers in an array.
BeginnerUse the reduce method.
Full Answer:
Use the reduce method.
Code Example:
const sum = arr => arr.reduce((a, b) => a + b, 0);Implement a 'usePrevious' hook.
ExperienceUse useRef to store the previous value and update it in a useEffect after rendering.
Full Answer:
Use useRef to store the previous value and update it in a useEffect after rendering.
Code Example:
function usePrevious(value) {
const ref = useRef();
useEffect(() => { ref.current = value; });
return ref.current;
}How to throttle a function?
AdvancedEnsure the function only executes once per specified interval.
Full Answer:
Ensure the function only executes once per specified interval.
Code Example:
function throttle(fn, limit) {
let lastFunc; let lastRan;
return function() {
if (!lastRan) { fn.apply(this, arguments); lastRan = Date.now(); }
else { ... }
}
}Check if two arrays are equal.
BeginnerCompare lengths and every element.
Full Answer:
Compare lengths and every element.
Code Example:
const equals = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);Merge two sorted arrays efficiently.
ExperienceUse two pointers to compare elements and push the smaller one.
Full Answer:
Use two pointers to compare elements and push the smaller one.
Code Example:
function merge(a, b) { ... }Implement Fibonacci sequence (recursive).
BeginnerSum of two previous digits.
Full Answer:
Sum of two previous digits.
Code Example:
const fib = n => n <= 1 ? n : fib(n - 1) + fib(n - 2);FizzBuzz implementation in JS.
BeginnerClassic problem using modulo operators.
Full Answer:
Classic problem using modulo operators.
Code Example:
for(let i=1;i<=100;i++) {
console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i);
}Detecting Prime numbers.
BeginnerLoop from 2 to sqrt(n) and check divisibility.
Full Answer:
Loop from 2 to sqrt(n) and check divisibility.
Code Example:
const isPrime = n => {
for(let i=2, s=Math.sqrt(n); i<=s; i++) if(n%i===0) return false;
return n > 1;
};Capitalize the first letter of each word.
BeginnerSplit string and map words to upper case first index.
Full Answer:
Split string and map words to upper case first index.
Code Example:
const cap = s => s.split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' ');Find the missing number in an array (1 to N).
ExperienceCalculate expected sum and subtract actual sum.
Full Answer:
Calculate expected sum and subtract actual sum.
Code Example:
const missing = (arr, n) => (n * (n + 1) / 2) - arr.reduce((a, b) => a + b);How to handle infinite scrolling?
AdvancedUse Intersection Observer API to detect when the user reaches the bottom.
Full Answer:
Use Intersection Observer API to detect when the user reaches the bottom.
Code Example:
new IntersectionObserver(([e]) => {
if(e.isIntersecting) loadMore();
}).observe(loaderRef.current);Creating a controlled vs uncontrolled component (Code).
BeginnerControlled uses state, uncontrolled uses ref.
Full Answer:
Controlled uses state, uncontrolled uses ref.
Code Example:
// Controlled
<input value={val} onChange={e => setVal(e.target.value)} />
// Uncontrolled
const ref = useRef(); <input ref={ref} />Using 'useMemo' for expensive sorting.
ExperienceMemoize the result of a sort to prevent re-sorting on every render.
Full Answer:
Memoize the result of a sort to prevent re-sorting on every render.
Code Example:
const sorted = useMemo(() => items.sort(), [items]);Generating a random color in JS.
BeginnerGenerate random hex values.
Full Answer:
Generate random hex values.
Code Example:
const randomColor = () => '#' + Math.floor(Math.random()*16777215).toString(16);Implementing a Countdown Timer.
ExperienceUse setInterval within useEffect and clean it up.
Full Answer:
Use setInterval within useEffect and clean it up.
Code Example:
useEffect(() => {
const id = setInterval(() => setTime(t => t - 1), 1000);
return () => clearInterval(id);
}, []);Finding duplicate numbers in an array.
BeginnerUse filter and indexOf.
Full Answer:
Use filter and indexOf.
Code Example:
const findDupes = arr => arr.filter((v, i) => arr.indexOf(v) !== i);How to use 'useCallback' to prevent unnecessary child renders?
ExperienceMemoize high-cost functions passed as props.
Full Answer:
Memoize high-cost functions passed as props.
Code Example:
const handleClick = useCallback(() => doSomething(id), [id]);Convert snake_case to camelCase.
BeginnerRegex replace with upper case function.
Full Answer:
Regex replace with upper case function.
Code Example:
const toCamel = s => s.replace(/(_\w)/g, m => m[1].toUpperCase());Implement a simple Pub/Sub pattern.
AdvancedAn object with subscribe, unsubscribe, and publish methods.
Full Answer:
An object with subscribe, unsubscribe, and publish methods.
Code Example:
const PubSub = { events: {}, subscribe(name, fn) { ... }, publish() { ... } };Extract numeric values from a string.
BeginnerUse match with a digits regex.
Full Answer:
Use match with a digits regex.
Code Example:
const getNumbers = s => s.match(/\d+/g);Calculating Factorial (Iterative).
BeginnerLoop from 1 to n multiplying results.
Full Answer:
Loop from 1 to n multiplying results.
Code Example:
const factor = n => { let r=1; for(let i=2;i<=n;i++) r*=i; return r; };Using 'useId' for accessible labels (Code).
BeginnerGenerate stable unique IDs.
Full Answer:
Generate stable unique IDs.
Code Example:
const id = useId();
<label htmlFor={id}>Name</label><input id={id} />How to prevent memory leaks with AbortController?
AdvancedInitialize AbortController and pass its signal to fetch.
Full Answer:
Initialize AbortController and pass its signal to fetch.
Code Example:
const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal });
return () => ctrl.abort();Find the second largest number in an array.
ExperienceSort descending and take second unique value.
Full Answer:
Sort descending and take second unique value.
Code Example:
const secondLarge = arr => [...new Set(arr)].sort((a,b)=>b-a)[1];Implementing a 'useWindowSize' hook.
BeginnerUpdate state on window 'resize' event.
Full Answer:
Update state on window 'resize' event.
Code Example:
const useWinSize = () => {
const [size, setSize] = useState({ w: window.innerWidth, h: window.innerHeight });
useEffect(() => {
const handle = () => setSize({ w: window.innerWidth, h: window.innerHeight });
window.addEventListener('resize', handle);
return () => window.removeEventListener('resize', handle);
}, []);
return size;
};Deep merge two objects.
AdvancedRecursively merge properties to preserve nested structures.
Full Answer:
Recursively merge properties to preserve nested structures.
Code Example:
const deepMerge = (a, b) => { ... }Fetch multiple URLs concurrently.
ExperienceUse Promise.all with an array of fetches.
Full Answer:
Use Promise.all with an array of fetches.
Code Example:
const results = await Promise.all(urls.map(u => fetch(u).then(r=>r.json())));Shuffle an array randomly.
BeginnerUse Fisher-Yates algorithm.
Full Answer:
Use Fisher-Yates algorithm.
Code Example:
const shuffle = arr => arr.sort(() => Math.random() - 0.5);Removing specific value from array.
BeginnerFilter out the value.
Full Answer:
Filter out the value.
Code Example:
const removeVal = (arr, val) => arr.filter(item => item !== val);Implement a 'useUpdateEffect' hook.
ExperienceA hook that skips the first run (on mount).
Full Answer:
A hook that skips the first run (on mount).
Code Example:
const isFirst = useRef(true);
useEffect(() => {
if(isFirst.current) { isFirst.current = false; return; }
fn();
}, deps);Checking for empty object.
BeginnerCheck Object.keys(obj).length === 0.
Full Answer:
Check Object.keys(obj).length === 0.
Code Example:
const isEmpty = obj => Object.keys(obj).length === 0 && obj.constructor === Object;Calculating average of array numbers.
BeginnerSum divided by length.
Full Answer:
Sum divided by length.
Code Example:
const avg = arr => arr.reduce((a,b)=>a+b,0) / arr.length;Generating UUID v4 in JS.
ExperienceUse crypto.randomUUID() or a specific generator function.
Full Answer:
Use crypto.randomUUID() or a specific generator function.
Code Example:
const uuid = () => crypto.randomUUID();Creating a custom context provider wrapper.
BeginnerA component that manages state and provides it to children.
Full Answer:
A component that manages state and provides it to children.
Code Example:
const Provider = ({ children }) => {
const [state, set] = useState();
return <Ctx.Provider value={{state, set}}>{children}</Ctx.Provider>
};Handling Form Data easily with JavaScript.
BeginnerUse the new FormData constructor.
Full Answer:
Use the new FormData constructor.
Code Example:
const handleSubmit = e => {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.target));
};