是从https://www.geeksforgeeks.org/reactjs/react-interview-questions/获取的。

 

ReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. It is widely used by companies like Facebook, Instagram, Netflix, and Airbnb because of its flexibility and performance.

Key aspects of React are:

Basic Level

Basic React Interview Questions

1. How does React.js work?

React.js works on a component-based architecture and uses a virtual DOM to efficiently update and render user interfaces.

working_of_react-

2. What is JSX and how is it converted into JavaScript?

Example of JSX: The name written in curly braces { } signifies JSX

Browsers can’t understand JSX directly. Instead, tools like Babel transpile it into plain JavaScript using React.createElement().

Babel converts it into:

3. What is a React component?

A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier.

In React, we mainly have two types of components:

4. Difference between functional and class component in React?

Functional Components Class Components
A functional component is just a plain JavaScript pure function that accepts props as an argument A class component requires you to extend from React. Component and create a render function
No render method usedIt must have the render() method returning JSX
Also known as Stateless components Also known as Stateful components
React lifecycle methods (for example, componentDidMount) cannot be used in functional components.React lifecycle methods can be used inside class components (for example, componentDidMount).
Constructors are not used.Constructor is used as it needs to store state.
Uses hooks like useState for managing state.Uses this.state and this.setState for state management

5. What are props and default props in React?

React allows us to pass information to a Component using something called props (which stands for properties). Props are objects which can be used inside a component. We can access any props inside from the component’s class to which the props is passed. The props can be accessed as shown below:

Default props are fallback values assigned to a component’s props when the parent does not provide them. They help prevent undefined errors and make components more robust. Default props can be defined using:

6. What is state in React and how do you update it?

State is the internal, mutable data of a React component that controls its behavior and rendering. When state changes, React re-renders the component to update the UI.

State is updated using setState() in class components or the useState setter function in functional components. Updates are asynchronous and can be triggered by events, user interactions, or API responses. When new state depends on the previous state, the functional form (setState(prev => ...)) should be used.

7. Difference Between Props and State in React?

PROPSSTATE
The Data is passed from one component to another.The Data is passed within the component only.
It is Immutable (cannot be modified).It is Mutable ( can be modified).
Props can be used with state and functional components.The state can be used only with the state components/class component (Before 16.0).
Props are read-only.The state is both read and write.
Example: Passing a title or onClick handler to a button component.Example: A counter value that increases when you click a button.

8. What are fragments in React?

In React, fragments allow you to group multiple elements without adding extra nodes to the DOM. Normally, returning multiple elements requires a wrapper like a <div>, which can create unnecessary DOM elements. Fragments solve this by letting you return multiple elements without extra wrappers.

9. What is the difference between controlled and uncontrolled components?

Controlled ComponentsUncontrolled Components
The React state controls the form input value.The DOM manages the input value.
Every change in input updates the state via onChange.React uses ref to access the current value when needed.
Provides full control over input data.Less code, simpler for basic forms.
Useful for validation, conditional rendering, or complex forms.Less control over validation and state management.

10. How does the DOM manage the input value in uncontrolled components?

React does not manage the form input’s state. Instead, the DOM itself keeps track of the input’s value. You can access the value when needed using refs

React Hooks Interview Questions

11. What are Hooks in React and why were they introduced?

Hooks are special functions in React that let you use state, lifecycle methods, and other React features in functional components, which were previously only available in class components.

Why introduced:

12. How does the useState hook work?

The useState hook allows you to add state to functional components. It returns a state variable and a setter function to update that state. When the state changes, React re-renders the component with the updated value.

Example:

In this example:

13. What is useEffect in React and what is the role of its dependency array?

useEffect is a React hook that allows functional components to perform side effects such as fetching data, setting up subscriptions, or directly manipulating the DOM. It runs after the component renders, ensuring the UI is updated first.

The dependency array controls when the effect runs:

useEffect can also return a cleanup function that runs on unmount or before the next effect, helping prevent memory leaks.

Example :

14. What is the difference between useEffect and useLayoutEffect?

useEffectuseLayoutEffect
Runs after render and paintingRuns before painting, after DOM updates
Non-blockingBlocking
Used for data fetching, subscriptions, timersUsed for reading layout, measuring DOM, or sync DOM updates
Safer for most side effectsCan slow rendering if heavy logic is used
Runs after every render by default (or based on dependency array)Use when DOM measurements are needed before painting

15. What is the useContext hook and when should you use it?

The useContext hook allows functional components to consume values from a React Context without passing props through every level of the component tree (avoiding “prop drilling”).

When to use it:

16. What is the useReducer hook and when is it preferred over useState?

The useReducer is a React hook used to manage complex state logic in functional components. It works similarly to Redux: you define a reducer function that takes the current state and an action, and returns a new state.

Example:

In this example:

Preferred over useState when:

17. What is the useRef hook and what are its common use cases?

The useRef hook creates a mutable object that persists across renders without causing re-renders. It is commonly used to access DOM elements or store mutable values.

Example:

In this example:

Common use cases:

18. Explain the difference between useMemo and useCallback?

useMemouseCallback
Memoizes computed valuesMemoizes functions
Returns the result of a functionReturns the function itself
Avoids expensive recalculations on re-renderPrevents re-creating functions on re-render
Improves performance by caching valuesImproves performance by avoiding unnecessary renders
Key idea: caches valueKey idea: caches function
Syntax: useMemo(() => computeValue(a, b), [a, b])Syntax: useCallback(() => handleClick(id), [id])

19. What are custom hooks in React and how do you create one?

Custom hooks are reusable functions that let you extract and share logic between functional components. They are JavaScript functions whose names start with use and can call other hooks like useState or useEffect.

Example:

In this example, useFetch is a custom hook that fetches data from an API and manages loading state. The hook is reused in App to keep the component clean and separate the data-fetching logic.

20. What are the rules of hooks and why are they important?

Hooks in React must follow certain rules to work correctly. These rules ensure that React can track state and effects reliably and prevent unexpected bugs.

Why they are important:

React State Management Interview Questions

21. What is State Management in React and what is the difference between Local and Global State?

State management refers to how an application handles and shares data across components. It ensures that the UI is updated correctly whenever the underlying data (state) changes. In React, state can be managed locally (inside components) or globally (shared across multiple components using context, Redux, Zustand, etc.).

Local StateGlobal State
Data managed within a single component.Data shared across multiple components.
Controlled using useState or useReducer inside the component.Managed using Context API, Redux, Zustand, etc.
Used for UI-related data like form inputs, modals, or toggles.Used for app-wide data like authentication, user info, or theme

22. What are some popular state management solutions in React/Next.js?

There are several approaches and libraries for managing state in React and Next.js, depending on the scale and complexity of your application:

23. When should you use Redux over Context API?

Choosing between Redux and Context API depends on the size and complexity of your application:

Use Redux when:

Use Context API when:

24. What is the difference between Client State and Server State?

Client StateServer State
Managed locally in the appManaged on backend/server
Controlled by useState, useReducer, ContextControlled via API or DB
Short-lived (browser session)Persistent across sessions/users
Examples: form inputs, UI togglesExamples: user data, product list

25. Explain the Context API in React.

The Context API in React is used to share data globally across components without prop drilling. It allows you to wrap components with a provider and access the shared value anywhere in the tree using useContext.createContext() : Creates a context.

26. What is the role of useReducer in state management?

The useReducer hook in React plays an important role in state management when the logic for updating state is complex or involves multiple actions. Unlike useState, which is best for simple state updates, useReducer organizes state transitions using a reducer function, making the code more predictable and easier to maintain. It is especially useful in larger applications or when managing related pieces of state.

27. How do you handle persistent state in React apps?

Persistent state ensures that certain data remains available even after page reloads or across sessions. Common approaches include:

28. What is the difference between derived state and computed state in React?

In React, sometimes you need values that depend on other state or props. These values can be handled as derived state or computed state, but they work differently:

29. How can you optimize state updates for performance in React?

Optimizing state updates ensures that components re-render only when necessary, improving performance in React applications:

30. How do you handle asynchronous state updates in React?

In React, state updates are asynchronous, so you need to handle them carefully to ensure predictable results:

React Rendering & Performance Questions:

31. Can you explain what the Virtual DOM is and how React uses it?

The Virtual DOM (VDOM) is a lightweight, in-memory representation of the real DOM in the browser. Instead of updating the actual DOM directly, which can be slow and costly, React first updates the Virtual DOM when a component’s state or props change. React then compares the new Virtual DOM with the previous one using a process called diffing, identifies the minimum set of changes needed, and updates only those parts of the real DOM. This approach makes UI updates faster and more efficient by reducing unnecessary DOM manipulations. Key points:

32. What do you understand by reconciliation in React? Why is it important?

Reconciliation in React is the process of comparing the new Virtual DOM with the previous one to determine what has changed. React then updates only the necessary parts of the real DOM, instead of re-rendering the entire UI. This approach improves performance, rendering speed, and efficiency, ensuring a smooth and responsive user experience. Key points:

33. How does React.memo help improve performance?

React.memo is a higher-order component that prevents unnecessary re-renders of functional components. It re-renders a component only if its props have changed, which helps improve performance in components that render frequently or are part of large lists.

Example: If you have a large list of items and only one item changes, React.memo ensures that the other list items do not re-render, saving processing time and improving UI performance.

34. If I ask you to optimize a slow React application, what techniques would you use?

To improve performance in a slow React application, you can use several optimization techniques:

35. What do you mean by code splitting and lazy loading in React?

Code splitting and lazy loading are techniques used to improve performance by reducing the initial load time of a React application.

In React, this is often implemented with React.lazy and <Suspense>:

36. How would you optimize a slow React application?

Optimizing a React application ensures faster rendering and better performance, especially for large or complex apps:

37. What is the difference between React.PureComponent and React.Component?

Both Component and PureComponent are used to create class components, but they handle re-rendering differently:

38. How does React handle re-rendering when state or props change?

Components automatically re-render when their state or props change, but React optimizes this process using the virtual DOM:

39. What is the difference between controlled and uncontrolled components in terms of rendering?

Form inputs can be controlled or uncontrolled, and this affects how they are rendered and updated:

40. How do useMemo and useCallback help improve performance in React?

In React, re-renders can be expensive if functions or computed values are recreated unnecessarily. useMemo and useCallback help optimize rendering by caching values and functions:

React Arrays & Lists Questions:

41. How do you render a list of items in React?

In React, lists are usually rendered using JavaScript’s .map() method. Each list item should also have a unique key prop so React can efficiently track and update elements.

In this Example, .map() is used to iterate over the array, and the key prop helps React identify each list item uniquely.

42. Why is the key prop important in React lists?

The key prop is important because it helps React efficiently manage list rendering. It allows React to identify which items have changed, been added, or removed, instead of re-rendering the entire list.

43. What happens if we use the array index as a key in React?

Using the array index as a key technically works, but it is not recommended in most cases. If the list changes (items are reordered, added, or removed), React may reuse components incorrectly, leading to UI bugs.

44. How do you conditionally render list items in React?

In React, list items can be conditionally rendered using techniques like if statements, ternary operators, or array methods such as .filter() combined with .map().

Example:

45. How do you update or remove an item from a list in React state?

State is immutable, so you cannot modify arrays directly. Instead, you create a new array using methods like .map() or .filter() and then update state with that new array.

Example (removing an item):

In this example, .filter() creates a new array without the removed item, and setList updates the state.

46. What are some performance tips when rendering large lists in React?

Rendering very large lists can hurt performance, so React provides techniques and best practices to optimize them:

47. How would you render a nested list in React?

You can nest .map() calls: one for the parent array and another for the child array.

Example:

In this example, each level of data gets its own .map() loop, and both parent and child elements should have unique key props.

48. How do you handle dynamic addition of items in a list?

In React, since state is immutable, you cannot directly modify the existing array. Instead, you create a new array that includes the new item and update state.

Example:

In this example:

49. How do you handle dynamic sorting or filtering of lists in React?

In React, lists are usually stored in state, and you can sort or filter them dynamically by creating a new array based on the original list and updating the state.

Example:

In this example:

50. What is the difference between rendering lists with map() vs forEach()?

When rendering lists, it’s important to return JSX elements for each item. The choice between map() and forEach() affects this:

Example using map():

In this example:

React Forms & Events Questions:

51. How are forms handled in React compared to plain HTML?

In plain HTML, the browser’s DOM manages form data. In React, form inputs are usually controlled components:

In this example, the input is fully controlled by React through value and onChange.

52. How do you prevent the default form submission behavior in React?

By using event.preventDefault() inside the form’s onSubmit handler.

Example:

In this example, the page is stopped from reloading and lets React control what happens on submit.

53. What is event bubbling and how can you stop it in React?

54. How do you handle multiple input fields in a single form in React?

By using a single state object and updating it dynamically with name and value.

Example:

This way, one handler can manage multiple inputs.

55. How do you reset form fields after submission in React?

In React, form inputs are usually controlled components, meaning their values are stored in state. To reset a form, you simply reset the state that controls the inputs:

Example:

In this example:

React Routing Questions:

56. What is React Router and why is it used?

React Router is a library that enables client-side routing in React applications. It allows you to create single-page applications (SPAs) where navigation between views happens without a full page reload, making apps faster and smoother.

57. Difference between <a> tag and <Link> in React Router?

58. What are the main components of React Router?

59. What is the difference between useHistory and useNavigate?

60. How do you implement nested routes in React Router?

/dashboard/profile : shows Profile inside Dashboard.

61. What are route parameters and how do you access them?

Route params are dynamic parts of the URL.

Inside User component:

/users/101 : id = 101

62. How do you redirect a user in React Router?

Using useNavigate() hook for programmatic redirects.

63. What is the difference between client-side routing and server-side routing?

Client-Side Routing

Example Flow:

Server-Side Routing

In server-side routing, whenever a user clicks a link or enters a URL:

Example Flow:

64. Difference between <Switch> and <Routes> in React Router

Switch:

Example:

Routes:

Example:

 

This React Interview Questions and Answers covers a wide range of topics, from basic concepts to advanced techniques. Whether you're a beginner or an experienced developer, mastering these questions will enhance your readiness for React interviews and boost your confidence.

Advanced Level

React Advanced Interview Questions - 2025

This set contains the advanced-level questions asked in the interview.

1. What are custom hooks in React?

Custom hooks are normal JavaScript functions whose names start with “use”, and they may call other hooks. We use custom hooks to maintain the DRY concept, which is Don't Repeat Yourself. It helps us to write a logic once and use it anywhere in the code. Some of the commonly used custom hooks are:

2. How to optimize a React code?

We can improve our React code by following these practices:

3. What is the difference between useref and createRef in React ?

FeatureuseRefcreateRef
TypeIt is a type of hook.It is a function.
Component TypeUsed in functional components.Used in class components.
Re-render BehaviorIt saves its value between re-renders in a functional component.It creates a new ref for every re-render.
Ref ValueReturns a mutable ref object ({ current: value }).Returns a new ref object every time.
Use CasesStoring DOM references, instance variables, and previous state values without re-renders.Storing DOM references in class components.
Exampleconst ref = useRef(null);this.ref = React.createRef();

4. What is React Redux?

React Redux is a state management tool which makes it easier to pass these states from one component to another irrespective of their position in the component tree and hence prevents the complexity of the application. As the number of components in our application increases it becomes difficult to pass state as props to multiple components. To overcome this situation we use react-redux.

5. What are the benefits of using react-redux?

There are several benefits of using react-redux such as

6. Explain the core components of react-redux.

There are four fundamental concepts of redux in react which decide how the data will flow through components

7. How can we combine multiple reducers in React?

When working with Redux we sometimes require multiple reducers. In many cases, multiple actions are needed, resulting in the requirement of multiple reducers. However, this can become problematic when creating the Redux store. To manage the multiple reducers we have function called combineReducers in the redux. This basically helps to combine multiple reducers into a single unit and use them.

Syntax

8. What is context API?

Context API is used to pass global variables anywhere in the code. It helps when there is a need for sharing state between a lot of nested components. It is light in weight and easier to use, to create a context just need to call React.createContext(). It eliminates the need to install other dependencies or third-party libraries like redux for state management. It has two properties Provider and Consumer.

9. Explain provider and consumer in ContextAPI?

A provider is used to provide context to the whole application whereas a consumer consume the context provided by nearest provider. In other words The Provider acts as a parent it passes the state to its children whereas the Consumer uses the state that has been passed.

10. Explain CORS in React.Axios

In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there.

We can setup CORS evironment in frontend using two methods:

11. What is axios and how to use it in React?

Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.

To install aixos package in react use the following command.

12. Write a program to create a counter with increment and decrement.

Output:

Animationkk

In this example

13. Explain why and how to update state of components using callback?

It is advised to use a callback-based approach to update the state using setState because it solves lots of bugs upfront that may occur in the future.We can use the following syntax to update the state using a callback.

14. What is React-Material UI?

React Material UI is a framework built upon React library which contains predefined components to create React applications. Material UI is basically a design language built by Google in 2014 and works with various JavaScript frameworks apart from React such as Angular.js and Vue.js. The quality of the inbuilt designs of Material UI and its easy implementation make it the first choice of most developers. The inbuilt components are also customizable so it helps easily recreate the designs.

15. What is flux architecture in redux?

Flux is an architecture that Facebook uses internally when operating with React. It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow.

16. Explain the useMemo hook in react?

The useMemo is a hook used in the functional component of react that returns a memoized value. In Computer Science, memoization is a concept used in general when we don’t need to recompute the function with a given argument for the next time as it returns the cached result. A memoized function remembers the results of output for a given set of inputs.

17. Does React useState Hook update immediately?

React do not update immediately, although it seems immediate at first glance. React keep track of the states by queuing them in the order they are called. React queue all the changes to be made and update once the component Re-render which is not immediate. This is how React knows which value corresponds to which state. It goes as per the queue every time the component tries to re-render.

18. When to use useCallback, useMemo and useEffect ?

19. Explain the types of router in React?

There are three types of routers in React:

20. What is StrictMode in React?

The React StrictMode can be viewed as a helper component that allows developers to code efficiently and brings to their attention any suspicious code which might have been accidentally added to the application. The StrictMode can be applied to any section of the application, not necessarily to the entire application.

21. What is Conditional Rendering in React?

Conditional rendering in React means dynamically displaying components or elements based on a condition. Instead of rendering everything at once, React decides what to render based on the current state, props, or logic. We can use conditional rendering when:

22. What is React Router?

React Router is a library for handling navigation in React applications. It allows developers to create single-page applications (SPAs) with multiple views while maintaining a smooth, seamless user experience without full-page reloads.

Let's now create the simple react router.

 

Output

In this example

Note: React 18 introduces this new way of rendering the app. The createRoot() method is now used instead of the old render() method to improve performance and enable new features like concurrent rendering.

23. What is the difference between the React Hooks and Classes?

FeatureReact HooksClass Components
State ManagementuseState() hook for state handling.this.state for state handling.
ReusabilityCustom hooks allow sharing logic across components.Inheritance is used for sharing logic, but it’s more complex.
this KeywordNo use of this. State and methods are directly accessible.Uses this to access state and methods (this.state, this.setState()).
Lifecycle MethodsuseEffect() for side effects and lifecycle management.Methods like componentDidMount(), componentDidUpdate(), etc.
PerformanceReact's new hooks API has better performance optimizations.Generally less efficient compared to functional components and hooks.

24. How Data is passed between the React Components?

In React, data is passed between components using props. The way data flows between components depends on whether they are parent-child, sibling components, or if you're using state management techniques like context or Redux.

25. What is Lazy Loading in React?

Lazy Loading in React is a technique used to load components only when they are needed, instead of loading everything at once when the app starts. This helps improve the performance of the app by reducing the initial loading time. In React, React.lazy() is used to implement lazy loading for components, which allows you to split your code into smaller bundles and load them only when required.

26. Explain Redux and its components.

Redux is a state management library that helps manage the application state globally. React-Redux is used to connect Redux state to React components. There are the three main components of the redux:

27. How React Routing is different from Conventional Routing?

React Routing is used in Single Page Applications (SPAs), while conventional routing typically applies to multi-page applications. Here’s how they differ:

FeaturesReact RoutingConventional Routing
Page LoadingNo full page reload; components are dynamically rendered.Entire page reload happens with every navigation.
SEO ConsiderationsReact Router needs additional configurations (like SSR or dynamic rendering) to optimize SEO.SEO is typically easier to manage since pages are fully rendered by the server.
NavigationNavigation is handled by JavaScript on the client-side, often using Link and NavLink components.Navigation is handled by the server through HTML anchor tags ().
TechnologyManaged via React Router; uses client-side routing.Managed by server-side routing (e.g., Express, PHP).
URL StructureURLs can have dynamic parameters handled by React Router (e.g., /product/:id).URLs are typically static and are managed by the server.

28. How to avoid binding in ReactJS?

In ReactJS, binding in the context of event handlers is often required to ensure that the correct this context is available inside class methods. However, it can lead to boilerplate code and performance issues, especially when binding functions in each render cycle. We can avoid binding in ReactJS by using the below methods:

29: What are props in React?

In React, props (short for "properties") are a way of passing data from a parent component to a child component. Props are read-only and are used to customize or control the behavior of a component. They help make components reusable and dynamic by allowing different data to be passed into them.

30. What is the use of CSS modules in React?

CSS Modules help you keep your styles specific to each React component, so they don't affect other components. In simple terms, it lets you write CSS for one component without worrying about messing up the styles of other parts of your app. This is especially useful when your app grows larger and has many components, making it easier to manage styles without conflicts.

Conclusion

ReactJS is an essential JavaScript library for building dynamic, high-performance UIs with reusable components. Mastering advanced topics like custom hooks, Redux, performance optimization, and state management will help you excel in React job interviews and advance your career in 2025.