React Interview Master

Curated 200+ Questions to Crack Your Next Tech Interview

0 / 200 LearnedProgramming FocusUpdated 2026
Showing 200 results in All Questions category.
1
What is React?
Beginner

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 ...

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.

Copy Answer Beginner
2
What is JSX?
Beginner

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(...

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.

Copy Answer Beginner
3
What are the core features of React?
Beginner

Core 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).

Copy Answer Beginner
4
What is the Virtual DOM?
Beginner

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 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.

Copy Answer Beginner
5
What are Components in React?
Beginner

Components 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.

Copy Answer Beginner
6
Difference between Functional and Class Components?
Beginner

Functional 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.

Copy Answer Beginner
7
What are Props?
Beginner

Props (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.

Copy Answer Beginner
8
What is State?
Beginner

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 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.

Copy Answer Beginner
9
What is the use of 'key' prop in lists?
Beginner

Keys 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.

Copy Answer Beginner
10
What is useState hook?
Beginner

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.

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.

Copy Answer Beginner
11
What is useEffect hook?
Beginner

useEffect 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.

Copy Answer Beginner
12
Explain One-way Data Binding.
Beginner

In 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.

Copy Answer Beginner
13
What is a Single Page Application (SPA)?
Beginner

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.

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.

Copy Answer Beginner
14
How do you handle events in React?
Beginner

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.

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.

Copy Answer Beginner
15
What is Conditional Rendering?
Beginner

Conditional 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.

Copy Answer Beginner
16
What is a React Fragment?
Beginner

Fragments 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 <>.</>

Copy Answer Beginner
17
What is 'create-react-app'?
Beginner

It'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.

Copy Answer Beginner
18
How do you add styles in React?
Beginner

Styles 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.

Copy Answer Beginner
19
What is the 'children' prop?
Beginner

The 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.

Copy Answer Beginner
20
What is the significance of 'className'?
Beginner

Since '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.

Copy Answer Beginner
21
What are Hook rules?
Beginner

Hooks 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.

Copy Answer Beginner
22
Difference between React and Angular?
Beginner

React 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.

Copy Answer Beginner
23
What is an event pooling?
Beginner

In 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.

Copy Answer Beginner
24
How to pass data from child to parent?
Beginner

Pass 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.

Copy Answer Beginner
25
What is the default port for React local server?
Beginner

The default port is 3000.

Full Answer:

The default port is 3000.

Copy Answer Beginner
26
What is the purpose of 'export default'?
Beginner

It 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.

Copy Answer Beginner
27
How to update state based on previous state?
Beginner

Pass 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).

Copy Answer Beginner
28
What is a Pure Component?
Beginner

A 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.

Copy Answer Beginner
29
What is the use of 'npm' in React?
Beginner

NPM (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.

Copy Answer Beginner
30
What is 'strict mode' in React?
Beginner

StrictMode 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.

Copy Answer Beginner
31
What is ReactDOM?
Beginner

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...

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.

Copy Answer Beginner
32
How to comment in JSX?
Beginner

Use curly braces with a block comment: {/* comment here */}.

Full Answer:

Use curly braces with a block comment: {/* comment here */}.

Copy Answer Beginner
33
What are Synthetic Events?
Beginner

React'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.

Copy Answer Beginner
34
What is a Controlled Input?
Beginner

An 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.

Copy Answer Beginner
35
What is an Uncontrolled Input?
Beginner

An 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.

Copy Answer Beginner
36
What is the difference between HTML and React events?
Beginner

HTML 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.

Copy Answer Beginner
37
What is Babel?
Beginner

Babel 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.

Copy Answer Beginner
38
What is Webpack?
Beginner

Webpack 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.

Copy Answer Beginner
39
How to prevent a component from rendering?
Beginner

Return '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.

Copy Answer Beginner
40
What is 'prop-types'?
Beginner

A 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.

Copy Answer Beginner
41
Difference between UI and Logic?
Beginner

UI 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.

Copy Answer Beginner
42
What is a higher-order component (basic)?
Beginner

A 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.

Copy Answer Beginner
43
What is the role of 'package.json'?
Beginner

It lists project metadata, dependencies, and scripts required for the application.

Full Answer:

It lists project metadata, dependencies, and scripts required for the application.

Copy Answer Beginner
44
How to handle forms in React?
Beginner

Forms 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.

Copy Answer Beginner
45
What is an Array Map in React?
Beginner

The .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.

Copy Answer Beginner
46
What is 'destructuring' in React?
Beginner

A 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.

Copy Answer Beginner
47
What is React.memo()?
Beginner

A 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.

Copy Answer Beginner
48
Importance of 'useEffect' dependency array?
Beginner

It 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.

Copy Answer Beginner
49
How to navigate between pages (basic)?
Beginner

Use 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.

Copy Answer Beginner
50
What is the 'public' folder for?
Beginner

It 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.

Copy Answer Beginner
51
Explain the Context API in detail.
Experience

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 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).

Copy Answer Experience
52
When to use useMemo vs useCallback?
Experience

useMemo 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).

Copy Answer Experience
53
How do you optimize React performance?
Experience

Using 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.

Copy Answer Experience
54
What are React Portals?
Experience

Portals 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).

Copy Answer Experience
55
Explain Error Boundaries.
Experience

Class 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.

Copy Answer Experience
56
How to handle global state without Redux?
Experience

Use 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.

Copy Answer Experience
57
What is useReducer hook?
Experience

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.

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.

Copy Answer Experience
58
Explain 'lifting state up'.
Experience

Moving 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.

Copy Answer Experience
59
What are custom hooks?
Experience

Functions 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.

Copy Answer Experience
60
Difference between useMemo and React.memo?
Experience

React.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.

Copy Answer Experience
61
Explain forwardRef.
Experience

A 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.

Copy Answer Experience
62
What is useRef and its common use cases?
Experience

useRef 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.

Copy Answer Experience
63
Explain React Router v6 features.
Experience

v6 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.

Copy Answer Experience
64
How to fetch data in useEffect properly?
Experience

Define 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.

Copy Answer Experience
65
What is the use of Layout components?
Experience

To 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.

Copy Answer Experience
66
How to implement Protected Routes?
Experience

Create 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.

Copy Answer Experience
67
Difference between server-side and client-side routing?
Experience

Server-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.

Copy Answer Experience
68
How to use the useContext hook?
Experience

Accepts 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.

Copy Answer Experience
69
What is 'Prop Drilling' and how to avoid it?
Experience

Passing 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.

Copy Answer Experience
70
Explain the concept of 'Render Props'.
Experience

A 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.

Copy Answer Experience
71
What is the difference between useLayoutEffect and useEffect?
Experience

useEffect 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).

Copy Answer Experience
72
How to optimize images in React?
Experience

Use 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.

Copy Answer Experience
73
What is Dependency Injection in React?
Experience

Passing 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.

Copy Answer Experience
74
Explain React's 'Reconciliation'.
Experience

The 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.

Copy Answer Experience
75
How to debug React applications?
Experience

Using React DevTools, browser debugger statement, console logs, and profiling tools.

Full Answer:

Using React DevTools, browser debugger statement, console logs, and profiling tools.

Copy Answer Experience
76
What is the 'key' warning in console?
Experience

Occurs 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.

Copy Answer Experience
77
How to handle large forms in React?
Experience

Use 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.

Copy Answer Experience
78
What is the Virtual DOM's 'Diffing' algorithm?
Experience

React 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.

Copy Answer Experience
79
Explain state persistence (localStorage) in React.
Experience

Initialize 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.

Copy Answer Experience
80
What are Higher-Order Components (HOC) examples?
Experience

withAuth (auth checks), connect (Redux), withRouter (legacy routing), or custom withLogger.

Full Answer:

withAuth (auth checks), connect (Redux), withRouter (legacy routing), or custom withLogger.

Copy Answer Experience
81
How to handle API errors globally?
Experience

Using 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.

Copy Answer Experience
82
Difference between Shadow DOM and Virtual DOM?
Experience

Shadow 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.

Copy Answer Experience
83
What is React.lazy and Suspense?
Experience

lazy 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.

Copy Answer Experience
84
What are fragments shorthand issues?
Experience

The <> 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}>.

Copy Answer Experience
85
How to use useImperativeHandle?
Experience

Customizes 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.

Copy Answer Experience
86
What is the importance of 'cleanup function' in useEffect?
Experience

Prevents 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.

Copy Answer Experience
87
How to fetch data derived from multiple state changes?
Experience

Include all relevant state variables in the useEffect dependency array.

Full Answer:

Include all relevant state variables in the useEffect dependency array.

Copy Answer Experience
88
Explain component composition vs inheritance.
Experience

React 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.

Copy Answer Experience
89
What is the 'batching' of updates?
Experience

React 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).

Copy Answer Experience
90
How to test components thoroughly?
Experience

Focus 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.

Copy Answer Experience
91
What is 'shallow rendering' in tests?
Experience

Testing 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).

Copy Answer Experience
92
How to handle accessibility (A11y) in React?
Experience

Use 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.

Copy Answer Experience
93
What is 'Hydration' in React?
Experience

The 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.

Copy Answer Experience
94
How to manage theme (Dark/Light) in React?
Experience

Use 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.

Copy Answer Experience
95
What is the use of 'debugger;' statement?
Experience

It 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.

Copy Answer Experience
96
How to fix 'Maximum update depth exceeded' error?
Experience

Check 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.

Copy Answer Experience
97
Explain the 'module' pattern in React project structure.
Experience

Grouping 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'.

Copy Answer Experience
98
How to use 'URL Search Params' in React?
Experience

Using 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.

Copy Answer Experience
99
What is React's Concurrent Mode?
Experience

A 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.

Copy Answer Experience
100
How to use SVGs effectively in React?
Experience

Import 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.

Copy Answer Experience
101
What is the React Fiber architecture?
Advanced

Fiber 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.

Copy Answer Advanced
102
Explain SSR, SSG, and ISR in Next.js.
Advanced

SSR: 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).

Copy Answer Advanced
103
How do you implement Micro-frontends with React?
Advanced

Using 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.

Copy Answer Advanced
104
Explain the 'useTransition' hook.
Advanced

Allows 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.

Copy Answer Advanced
105
What is the 'useDeferredValue' hook?
Advanced

Lets 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.

Copy Answer Advanced
106
How to handle memory leaks in large applications?
Advanced

Properly 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.

Copy Answer Advanced
107
Deep dive: Reconciliation and Diffing logic.
Advanced

React 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.

Copy Answer Advanced
108
Redux Saga vs Redux Thunk.
Advanced

Thunk 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.

Copy Answer Advanced
109
Explain Server Components in React 18.
Advanced

Components 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.

Copy Answer Advanced
110
What is 'Atomic State Management' (Recoil/Jotai)?
Advanced

Managing 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.

Copy Answer Advanced
111
How to implement Custom Middleware in Redux?
Advanced

A triple-curried function: (store) => (next) => (action) => { ... next(action); }.

Full Answer:

A triple-curried function: (store) => (next) => (action) => { ... next(action); }.

Copy Answer Advanced
112
Web Workers integration with React.
Advanced

Offloading 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).

Copy Answer Advanced
113
Security best practices: XSS and Data Sanitization.
Advanced

Don'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.

Copy Answer Advanced
114
Explain the 'Double Invoke' in StrictMode.
Advanced

React 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.

Copy Answer Advanced
115
What is 'Zustand' and why is it popular?
Advanced

A 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.

Copy Answer Advanced
116
Optimizing Web Vitals in a React app.
Advanced

Focusing 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).

Copy Answer Advanced
117
Explain 'Code Splitting' beyond React.lazy.
Advanced

Splitting 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.

Copy Answer Advanced
118
How does the 'useSyncExternalStore' hook work?
Advanced

Allows 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.

Copy Answer Advanced
119
Using 'useId' for unique identifiers.
Advanced

Generates 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.

Copy Answer Advanced
120
Explain 'Automatic Batching' in React 18.
Advanced

React 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.

Copy Answer Advanced
121
What is 'Tree Shaking'?
Advanced

Removing 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.

Copy Answer Advanced
122
Implementing complex animations (e.g., Framer Motion).
Advanced

Using layout animations, variants, and AnimatePresence for entering/exiting shared layouts.

Full Answer:

Using layout animations, variants, and AnimatePresence for entering/exiting shared layouts.

Copy Answer Advanced
123
Testing Hooks with renderHook.
Advanced

Using @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.

Copy Answer Advanced
124
How to handle 'Hydration Mismatch'?
Advanced

Ensure 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.

Copy Answer Advanced
125
Explain 'Streaming SSR'.
Advanced

Sending 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.

Copy Answer Advanced
126
What are 'Ref' utility patterns (e.g., Callback Refs)?
Advanced

Using 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.

Copy Answer Advanced
127
Architecture: Feature-Slicing Design (FSD).
Advanced

A 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.

Copy Answer Advanced
128
How to implement Multi-language (i18n) at scale?
Advanced

Using 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.

Copy Answer Advanced
129
Security: JWT storage (Cookie vs LocalStorage).
Advanced

Cookies (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.

Copy Answer Advanced
130
Explain 'Module Federation' in depth.
Advanced

A 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.

Copy Answer Advanced
131
Performance: Virtualization (react-window).
Advanced

Rendering 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.

Copy Answer Advanced
132
What is 'useInsertionEffect'?
Advanced

A 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.

Copy Answer Advanced
133
How to build a Design System with React?
Advanced

Creating 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.

Copy Answer Advanced
134
Handling Cross-tab Communication.
Advanced

Using BroadcastChannel API, localStorage events, or Shared Workers.

Full Answer:

Using BroadcastChannel API, localStorage events, or Shared Workers.

Copy Answer Advanced
135
Explain 'Command Pattern' in React.
Advanced

Decoupling 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).

Copy Answer Advanced
136
What is 'Preact' and when to use it?
Advanced

A 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.

Copy Answer Advanced
137
What is 'TanStack Query' (React Query)?
Advanced

A 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.

Copy Answer Advanced
138
Explain 'Finite State Machines' with XState.
Advanced

Modeling 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.

Copy Answer Advanced
139
Advanced usage of useReducer with Middleware.
Advanced

Wrapping dispatch to add logging or async handle capabilities to useReducer.

Full Answer:

Wrapping dispatch to add logging or async handle capabilities to useReducer.

Copy Answer Advanced
140
How to scale React applications for millions of users?
Advanced

CDN 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.

Copy Answer Advanced
141
What are 'React Native' differences?
Advanced

Uses 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.

Copy Answer Advanced
142
Explain 'Reflecting' state to URL.
Advanced

Keeping 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.

Copy Answer Advanced
143
How to optimize Context API re-renders?
Advanced

Splitting 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.

Copy Answer Advanced
144
What is 'Experimental React' branch?
Advanced

Features 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).

Copy Answer Advanced
145
Handling File Uploads at scale.
Advanced

Using 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.

Copy Answer Advanced
146
What is 'Isomorphic JavaScript'?
Advanced

JavaScript 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.

Copy Answer Advanced
147
Explain 'Duck Pattern' in Redux.
Advanced

Combining 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.

Copy Answer Advanced
148
Using 'Proxy' for state management.
Advanced

The 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.

Copy Answer Advanced
149
What is 'Shadowing' in Gatsby/Next.js?
Advanced

Customizing 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.

Copy Answer Advanced
150
Future of React: What's after React 18/19?
Advanced

React 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.

Copy Answer Advanced
151
How to implement a useLocalStorage hook?
Experience

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 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];
}
Copy Answer Programming
152
Reverse a string in JavaScript without built-in 'reverse'?
Beginner

Use a decrementing loop or reduce.

Full Answer:

Use a decrementing loop or reduce.

Code Example:
const reverseStr = str => [...str].reduce((acc, char) => char + acc, '');
Copy Answer Programming
153
Implement a simple counter with useReducer.
Beginner

Define 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;
  }
};
Copy Answer Programming
154
How to debounce a function in React?
Experience

Use 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]);
Copy Answer Programming
155
Find the longest word in a sentence.
Beginner

Split 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);
Copy Answer Programming
156
Remove duplicates from an array.
Beginner

Use 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)];
Copy Answer Programming
157
Implement a deep clone function.
Advanced

For 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));
Copy Answer Programming
158
Check if a string is a palindrome.
Beginner

Compare the string with its reversed version.

Full Answer:

Compare the string with its reversed version.

Code Example:
const isPalindrome = str => str === [...str].reverse().join('');
Copy Answer Programming
159
Convert a nested object to a flat URL query string.
Advanced

Recursively 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('&');
Copy Answer Programming
160
Flatten a nested array.
Experience

Use 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);
Copy Answer Programming
161
Count character occurrences in a string.
Beginner

Iterate 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 }), {});
Copy Answer Programming
162
Group an array of objects by a property.
Experience

Use 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;
}, {});
Copy Answer Programming
163
Implement a basic Fetch with error handling.
Beginner

Use 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); }
}
Copy Answer Programming
164
Create a simple Toggle hook.
Beginner

A 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];
}
Copy Answer Programming
165
Find the intersection of two arrays.
Beginner

Filter 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));
Copy Answer Programming
166
Sum of all numbers in an array.
Beginner

Use the reduce method.

Full Answer:

Use the reduce method.

Code Example:
const sum = arr => arr.reduce((a, b) => a + b, 0);
Copy Answer Programming
167
Implement a 'usePrevious' hook.
Experience

Use 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;
}
Copy Answer Programming
168
How to throttle a function?
Advanced

Ensure 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 { ... }
  }
}
Copy Answer Programming
169
Check if two arrays are equal.
Beginner

Compare 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]);
Copy Answer Programming
170
Merge two sorted arrays efficiently.
Experience

Use 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) { ... }
Copy Answer Programming
171
Implement Fibonacci sequence (recursive).
Beginner

Sum 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);
Copy Answer Programming
172
FizzBuzz implementation in JS.
Beginner

Classic 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);
}
Copy Answer Programming
173
Detecting Prime numbers.
Beginner

Loop 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;
};
Copy Answer Programming
174
Capitalize the first letter of each word.
Beginner

Split 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(' ');
Copy Answer Programming
175
Find the missing number in an array (1 to N).
Experience

Calculate 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);
Copy Answer Programming
176
How to handle infinite scrolling?
Advanced

Use 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);
Copy Answer Programming
177
Creating a controlled vs uncontrolled component (Code).
Beginner

Controlled 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} />
Copy Answer Programming
178
Using 'useMemo' for expensive sorting.
Experience

Memoize 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]);
Copy Answer Programming
179
Generating a random color in JS.
Beginner

Generate random hex values.

Full Answer:

Generate random hex values.

Code Example:
const randomColor = () => '#' + Math.floor(Math.random()*16777215).toString(16);
Copy Answer Programming
180
Implementing a Countdown Timer.
Experience

Use 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);
}, []);
Copy Answer Programming
181
Finding duplicate numbers in an array.
Beginner

Use filter and indexOf.

Full Answer:

Use filter and indexOf.

Code Example:
const findDupes = arr => arr.filter((v, i) => arr.indexOf(v) !== i);
Copy Answer Programming
182
How to use 'useCallback' to prevent unnecessary child renders?
Experience

Memoize high-cost functions passed as props.

Full Answer:

Memoize high-cost functions passed as props.

Code Example:
const handleClick = useCallback(() => doSomething(id), [id]);
Copy Answer Programming
183
Convert snake_case to camelCase.
Beginner

Regex 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());
Copy Answer Programming
184
Implement a simple Pub/Sub pattern.
Advanced

An 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() { ... } };
Copy Answer Programming
185
Extract numeric values from a string.
Beginner

Use match with a digits regex.

Full Answer:

Use match with a digits regex.

Code Example:
const getNumbers = s => s.match(/\d+/g);
Copy Answer Programming
186
Calculating Factorial (Iterative).
Beginner

Loop 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; };
Copy Answer Programming
187
Using 'useId' for accessible labels (Code).
Beginner

Generate stable unique IDs.

Full Answer:

Generate stable unique IDs.

Code Example:
const id = useId();
<label htmlFor={id}>Name</label><input id={id} />
Copy Answer Programming
188
How to prevent memory leaks with AbortController?
Advanced

Initialize 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();
Copy Answer Programming
189
Find the second largest number in an array.
Experience

Sort 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];
Copy Answer Programming
190
Implementing a 'useWindowSize' hook.
Beginner

Update 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;
};
Copy Answer Programming
191
Deep merge two objects.
Advanced

Recursively merge properties to preserve nested structures.

Full Answer:

Recursively merge properties to preserve nested structures.

Code Example:
const deepMerge = (a, b) => { ... }
Copy Answer Programming
192
Fetch multiple URLs concurrently.
Experience

Use 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())));
Copy Answer Programming
193
Shuffle an array randomly.
Beginner

Use Fisher-Yates algorithm.

Full Answer:

Use Fisher-Yates algorithm.

Code Example:
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
Copy Answer Programming
194
Removing specific value from array.
Beginner

Filter out the value.

Full Answer:

Filter out the value.

Code Example:
const removeVal = (arr, val) => arr.filter(item => item !== val);
Copy Answer Programming
195
Implement a 'useUpdateEffect' hook.
Experience

A 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);
Copy Answer Programming
196
Checking for empty object.
Beginner

Check 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;
Copy Answer Programming
197
Calculating average of array numbers.
Beginner

Sum divided by length.

Full Answer:

Sum divided by length.

Code Example:
const avg = arr => arr.reduce((a,b)=>a+b,0) / arr.length;
Copy Answer Programming
198
Generating UUID v4 in JS.
Experience

Use crypto.randomUUID() or a specific generator function.

Full Answer:

Use crypto.randomUUID() or a specific generator function.

Code Example:
const uuid = () => crypto.randomUUID();
Copy Answer Programming
199
Creating a custom context provider wrapper.
Beginner

A 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>
};
Copy Answer Programming
200
Handling Form Data easily with JavaScript.
Beginner

Use 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));
};
Copy Answer Programming