1. What is React?
React is a JavaScript library used for building user interfaces, primarily for single-page applications.
2. Who developed React?
React was developed by Facebook (now Meta) and is maintained by both Meta and the open-source community.
3. What are components in React?
Components are the building blocks of a React application. They are reusable pieces of UI that can be independent and composable.
4. What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML-like code inside JavaScript files.
5. What is the difference between functional and class components?
Functional components are simple JavaScript functions, whereas class components are ES6 classes that extend React.Component and can have state.
6. What is the virtual DOM in React?
The virtual DOM is a lightweight copy of the real DOM that React uses to improve performance by making efficient updates.
7. Why is React considered declarative?
React is declarative because it allows developers to describe the UI state and let React handle updating the DOM accordingly.
8. What are props in React?
Props (short for properties) are used to pass data from a parent component to a child component.
9. What is state in React?
State is an object that holds dynamic data and determines how a component renders and behaves.
10. How do you create a React application?
A React application can be created using the Create React App (CRA) command-line tool.
11. What is the purpose of ReactDOM?
ReactDOM is used to render React components into the actual DOM.
12. What is the difference between a controlled and an uncontrolled component?
A controlled component has its state managed by React, while an uncontrolled component manages its own state using the DOM.
13. What is the purpose of the useState hook?
The useState hook is used to add state to functional components.
14. What is the useEffect hook used for?
The useEffect hook is used to handle side effects such as fetching data, subscriptions, or manually changing the DOM.
15. How does React handle events?
React uses a synthetic event system, which is a wrapper around the browser’s native event system, to improve performance and compatibility.
16. What is a React fragment?
A React fragment is a way to group multiple elements without adding an extra node to the DOM.
17. What is the difference between props and state?
Props are immutable and passed from parent to child, whereas state is mutable and controlled within the component.
18. What is the role of keys in React lists?
Keys help React identify which items have changed, are added, or removed, improving performance.
19. What is the purpose of the useRef hook?
The useRef hook is used to reference a DOM element or persist values across renders without triggering re-renders.
20. What is conditional rendering in React?
Conditional rendering allows React to render different UI elements based on a condition.
21. What is React Router?
React Router is a library used for handling navigation and routing in React applications.
22. What is the difference between BrowserRouter and HashRouter?
BrowserRouter uses the HTML5 history API for navigation, while HashRouter uses URL hash-based navigation.
23. What is the purpose of context in React?
Context provides a way to pass data through the component tree without needing to pass props manually at every level.
24. How can you optimize performance in a React application?
Performance can be optimized using memoization, lazy loading, virtual lists, avoiding unnecessary re-renders, and using PureComponent.
25. What is React.memo?
React.memo is a higher-order component that prevents unnecessary re-renders by memoizing the result of a functional component.
26. What is lazy loading in React?
Lazy loading is a technique that delays loading components until they are needed, improving initial page load performance.
27. What is the difference between useState and useReducer?
useState is used for managing local component state, while useReducer is used for more complex state logic with dispatch actions.
28. What is a Higher-Order Component (HOC)?
A Higher-Order Component is a function that takes a component and returns a new enhanced component.
29. What is the purpose of the useCallback hook?
The useCallback hook is used to memoize functions and prevent unnecessary re-creations during re-renders.
30. What is the purpose of the useMemo hook?
The useMemo hook is used to memoize expensive computations and only recompute when dependencies change.
31. What is the purpose of error boundaries in React?
Error boundaries are React components that catch JavaScript errors in the component tree and display a fallback UI instead of crashing the application.
32. Can hooks be used inside class components?
No, hooks can only be used inside functional components.
33. What is the purpose of the useContext hook?
The useContext hook allows functional components to access values from a React context without needing a Consumer component.
34. How does React handle forms?
React handles forms using controlled components, where the form input values are managed by React state.
35. What is lifting state up in React?
Lifting state up is a pattern where the state is moved to a common ancestor component so that multiple child components can access and modify it.
36. What are portals in React?
Portals allow rendering a React component’s children into a different part of the DOM outside of its parent component’s hierarchy.
37. What is reconciliation in React?
Reconciliation is the process React uses to update the virtual DOM and apply changes efficiently to the real DOM.
38. What is PureComponent in React?
PureComponent is a class component that implements a shallow comparison of props and state to prevent unnecessary re-renders.
39. What is the difference between React and React Native?
React is a JavaScript library for building web applications, while React Native is a framework for building mobile applications using React.
40. What is a controlled component in React?
A controlled component is an input element whose value is controlled by React state rather than the DOM.
41. What is an uncontrolled component in React?
An uncontrolled component is an input element that maintains its own state using the DOM instead of React state.
42. What is the purpose of defaultProps in React?
defaultProps allow setting default values for props in case they are not provided by the parent component.
43. What is the significance of the key prop in React lists?
The key prop helps React identify which items have changed, been added, or removed, improving the efficiency of rendering lists.
44. What is server-side rendering (SSR) in React?
Server-side rendering is the process of rendering React components on the server and sending HTML to the client to improve performance and SEO.
45. What is hydration in React?
Hydration is the process where React takes over a server-rendered application and attaches event listeners to the existing HTML.
46. What is the difference between stateful and stateless components?
Stateful components manage local state, whereas stateless components do not maintain any state and rely on props.
47. How do you handle events in React?
Events in React are handled using event listeners written in JSX, with event handlers passed as functions.
48. What is the difference between shallow and deep comparison in React?
Shallow comparison checks only the first level of objects, while deep comparison checks all nested properties for equality.
49. What is the significance of the children prop in React?
The children prop allows components to receive and render nested elements or other components dynamically.
50. What is the difference between useEffect and componentDidMount?
useEffect is a hook used in functional components, whereas componentDidMount is a lifecycle method used in class components to run code after the component mounts.
51. What is the virtual DOM in React?
The virtual DOM is a lightweight copy of the real DOM that React uses to improve performance by minimizing direct DOM manipulations.
52. How does React update the real DOM?
React compares the virtual DOM with the previous version, finds differences (diffing), and updates only the changed parts in the real DOM.
53. What is the role of React Fiber?
React Fiber is the reconciliation algorithm introduced in React to improve rendering performance and responsiveness.
54. What is the difference between React.createElement and JSX?
React.createElement is a method to create elements manually, whereas JSX is a syntax extension that makes writing React components easier.
55. Why do we need to wrap multiple JSX elements inside a parent container?
JSX requires a single parent element because it must return a single node, which can be achieved using a div or React fragments.
56. What is the purpose of the useImperativeHandle hook?
The useImperativeHandle hook allows customizing the instance value exposed when using React.forwardRef.
57. What is the purpose of React.forwardRef?
React.forwardRef allows passing a ref from a parent component to a child component, giving direct access to the child’s DOM element.
58. What is the purpose of the useLayoutEffect hook?
The useLayoutEffect hook is similar to useEffect but runs synchronously after DOM mutations and before the browser paints the screen.
59. How do you update the state in React?
In class components, state is updated using setState, while in functional components, the useState setter function is used.
60. What is a functional component in React?
A functional component is a JavaScript function that returns JSX and does not have its own state or lifecycle methods unless using hooks.
61. What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML-like code in React components, which is later transformed into JavaScript.
62. How do you handle dynamic class names in React?
Dynamic class names can be handled using JavaScript expressions, template literals, or libraries like `classnames` to conditionally apply class names.
63. What is a component in React?
A component is a reusable, self-contained building block in React that can either be a function or a class, which returns a React element (UI).
64. What is prop drilling?
Prop drilling is the process of passing props from a parent component to a deeply nested child component, which can become cumbersome with deep component trees.
65. How can you avoid prop drilling in React?
Prop drilling can be avoided by using React Context or state management libraries like Redux or Zustand to share data globally without passing through multiple layers.
66. What is a state in React?
State is a JavaScript object that holds data that influences the rendering of components. It can be modified using `setState` in class components or a setter from `useState` in functional components.
67. How do you pass data from a parent to a child component?
Data can be passed from a parent to a child component via props, which are read-only and allow the parent to provide values to the child.
68. What is the purpose of React.Fragment?
React.Fragment is used to group multiple elements without adding an extra node to the DOM, helping avoid unnecessary wrapper elements.
69. What is the difference between React.Component and React.PureComponent?
React.Component is the base class for creating class components, while React.PureComponent is a subclass that implements a shallow comparison for prop and state changes, preventing unnecessary re-renders.
70. What is the role of the render method in React?
The render method in class components is responsible for returning the JSX that defines what the UI should look like.
71. What is the difference between props and state?
Props are immutable values passed from parent to child components, whereas state is mutable and managed within a component.
72. What are higher-order components (HOCs) in React?
A higher-order component is a function that takes a component and returns a new component, typically used to reuse component logic.
73. What is the use of useState in React?
useState is a hook that allows functional components to manage local state by returning a state variable and a setter function.
74. What is the difference between useEffect and useCallback in React?
useEffect runs side effects in functional components, whereas useCallback memoizes functions to prevent unnecessary re-creations between renders.
75. What is the purpose of React’s Suspense component?
React’s Suspense component is used to handle asynchronous loading of components, showing a fallback UI while waiting for content to load.
76. How do you optimize performance in React?
Performance can be optimized in React by using techniques such as memoization, lazy loading, code splitting, and shouldComponentUpdate for class components.
77. What is the useEffect hook used for?
The useEffect hook in functional components is used to perform side effects such as data fetching, subscriptions, or manually changing the DOM after render.
78. What are React refs used for?
React refs are used to directly access a DOM element or a class component instance for manipulating the DOM or invoking methods.
79. What is the role of the useRef hook?
useRef is a hook that creates a mutable object which persists across renders, often used to access DOM elements or store values without causing re-renders.
80. What is the React DevTools used for?
React DevTools is a browser extension that allows inspecting the React component tree, checking component props and state, and profiling performance.
81. What is JSX and why do we use it in React?
JSX is a syntax extension that allows us to write HTML-like code within JavaScript. It makes the React code more readable and easier to write.
82. What is ReactDOM?
ReactDOM is a package that provides methods to render React components to the DOM and manage the component lifecycle.
83. What is a functional component?
A functional component is a JavaScript function that accepts props as arguments and returns JSX to render the UI.
84. What is a class component?
A class component is a React component defined using a JavaScript class, which can manage its own state and have lifecycle methods.
85. What are React lifecycle methods?
Lifecycle methods are special methods that are invoked at different stages of a component's life, such as mounting, updating, and unmounting.
86. What is the purpose of the shouldComponentUpdate lifecycle method?
shouldComponentUpdate allows you to optimize performance by preventing unnecessary re-renders when props or state haven’t changed.
87. What is the difference between useState and useReducer?
useState is used for managing simple state, whereas useReducer is more suitable for managing complex state logic with multiple sub-values or actions.
88. What is React Router?
React Router is a library used to implement routing in React applications, allowing for navigation between different components based on the URL.
89. What is the difference between an uncontrolled and controlled component?
A controlled component is one whose state is controlled by React, while an uncontrolled component manages its own state through the DOM.
90. What is the Context API in React?
The Context API provides a way to share state globally across the component tree without passing props manually at each level.
91. What is the purpose of the useContext hook?
The useContext hook is used to access the value of a context directly in functional components, avoiding prop drilling.
92. How can you handle form data in React?
Form data can be handled using controlled components, where form elements' values are controlled by React state via the useState hook.
93. What is the purpose of the useMemo hook in React?
The useMemo hook is used to memoize expensive computations so that they are only recalculated when their dependencies change, improving performance.
94. What is the purpose of React’s key prop?
The key prop helps React identify which items in a list are changed, added, or removed, optimizing the rendering of lists.
95. How do you pass data between sibling components in React?
Data can be passed between sibling components via a common parent component, which holds the shared state and passes the data down as props.
96. What is the difference between useEffect and useLayoutEffect?
useEffect runs asynchronously after the render, while useLayoutEffect runs synchronously after DOM mutations but before the browser paints the screen.
97. What are React portals used for?
React portals allow rendering children into a different part of the DOM that is outside the parent component’s hierarchy, useful for modals or tooltips.
98. What is the use of the React.StrictMode component?
React.StrictMode is a wrapper component that helps identify potential problems in an application by activating additional checks and warnings in development mode.
99. What is the difference between functional components and class components in terms of performance?
Functional components are generally more lightweight and faster than class components, especially with hooks introduced in React 16.8.
100. What is the purpose of React’s Suspense and lazy?
React’s Suspense and lazy enable code splitting, allowing components to be loaded asynchronously and showing a fallback UI while the component is loading.
101. What is the difference between React’s state and props?
State is mutable and managed within a component, while props are immutable and passed from a parent to a child component.
102. How can you use React's useState hook?
useState is a hook that allows you to add state to functional components, returning a state variable and a function to update it.
103. What is the purpose of React’s useEffect hook?
useEffect allows you to perform side effects in functional components, such as fetching data, setting up subscriptions, or manipulating the DOM after render.
104. What is the difference between an inline style and CSS classes in React?
Inline styles are written directly in JSX as objects, whereas CSS classes are defined in external stylesheets and referenced via the `className` attribute.
105. How can you handle events in React?
Events in React are handled by defining event handlers, such as `onClick`, `onChange`, etc., and passing them to elements as props.
106. What is the purpose of the React key prop?
The key prop is used to identify unique elements in a list, helping React to efficiently update and re-render components without unnecessary changes.
107. How do you bind event handlers in React?
Event handlers can be bound in the constructor for class components or directly in the JSX for functional components using arrow functions.
108. What is a functional component?
A functional component is a stateless component in React that is defined using a JavaScript function and returns JSX.
109. What is the use of the React.Fragment?
React.Fragment is used to group multiple elements without adding extra nodes to the DOM, helping to keep the DOM tree clean.
110. What are controlled components in React?
Controlled components are form elements whose value is controlled by React state, allowing for greater control over user inputs and validation.
111. What is the difference between class components and functional components?
Class components are ES6 classes that can hold state and lifecycle methods, while functional components are simple JavaScript functions that use hooks for state and side effects.
112. How do you update state in React?
State can be updated using the `setState` method in class components or the setter function returned by the `useState` hook in functional components.
113. What are side effects in React, and how can you manage them?
Side effects in React include tasks like fetching data or subscribing to external events. They are managed using the `useEffect` hook in functional components.
114. What is the significance of the `componentDidMount` lifecycle method?
`componentDidMount` is called once after the component has been rendered and is often used to perform setup tasks such as data fetching.
115. What is the `useReducer` hook in React?
The `useReducer` hook is used to manage complex state logic in a functional component, allowing you to dispatch actions and handle state transitions based on them.
116. How do you handle errors in React?
Errors can be handled using `Error Boundaries` for class components or try-catch blocks in asynchronous functions within `useEffect` or other hooks in functional components.
117. What is the `render` method in React?
The `render` method is a lifecycle method in class components that returns the JSX to be rendered to the screen.
118. What is the importance of keys in a list of elements in React?
Keys help React identify which items in a list are changed, added, or removed, ensuring efficient re-renders and updates to the list.
119. What is React’s Virtual DOM?
The Virtual DOM is a lightweight representation of the actual DOM that allows React to perform efficient updates by comparing the current state with the previous one and only applying changes where necessary.
120. How do you make AJAX requests in React?
AJAX requests in React can be made using JavaScript’s `fetch` API or third-party libraries like Axios, typically inside `useEffect` for functional components.
1. What are higher-order components (HOCs) in React?
A higher-order component is a function that takes a component and returns a new component with additional props or behavior. HOCs are used for code reuse and logic abstraction.
2. How do you manage forms with multiple inputs in React?
Forms with multiple inputs can be managed by using controlled components, where each input’s value is bound to a piece of state and updated via event handlers.
3. What is the difference between useEffect and useLayoutEffect?
`useEffect` runs asynchronously after the render, whereas `useLayoutEffect` runs synchronously before the browser repaints, useful for making DOM mutations.
4. What are React context and when would you use it?
React Context provides a way to share values across components without passing them explicitly as props. It is useful for global data like themes, authentication status, etc.
5. What are render props in React?
Render props is a technique for sharing code between components using a function prop that returns JSX. The function receives arguments from the component and is called during rendering.
6. How can you optimize performance in React?
Performance in React can be optimized by memoizing components with `React.memo`, using the `useMemo` and `useCallback` hooks, lazy loading components, and avoiding unnecessary renders.
7. What is React's reconciliation algorithm?
The reconciliation algorithm is responsible for comparing the Virtual DOM with the actual DOM and determining the most efficient way to update the actual DOM with minimal changes.
8. What is `React.memo`?
`React.memo` is a higher-order component that optimizes the performance of functional components by memoizing them, preventing unnecessary re-renders when the props have not changed.
9. What is prop drilling and how can you avoid it?
Prop drilling is the process of passing props through multiple levels of components, which can become cumbersome. It can be avoided using context or state management libraries like Redux or MobX.
10. How do you handle side effects in functional components?
Side effects in functional components are handled by using the `useEffect` hook, which allows you to perform operations like fetching data, subscribing to events, or manually updating the DOM.
11. What is the `useRef` hook in React and how is it used?
`useRef` is a hook that allows you to persist values across renders without causing re-renders. It can be used for accessing DOM elements or storing mutable values.
12. How do you handle conditional rendering in React?
Conditional rendering in React can be handled using JavaScript operators like `if`, ternary operators, or logical `&&` to determine which components or elements should be rendered.
13. What is the `useCallback` hook in React?
`useCallback` is a hook that returns a memoized version of a function, preventing unnecessary re-creations of functions on every render, optimizing performance in certain scenarios.
14. How do you handle errors in React applications?
Errors in React applications can be handled using error boundaries, which catch JavaScript errors in the component tree and display a fallback UI. Alternatively, `try-catch` can be used in asynchronous operations.
15. What is code splitting and how can you implement it in React?
Code splitting is the practice of breaking down the code into smaller chunks, which can be loaded on demand to improve the application's performance. It can be implemented using `React.lazy()` and `Suspense`.
16. How does React’s `useState` hook work?
The `useState` hook allows functional components to hold and manage state by returning a state variable and a function to update it.
17. What is the `useContext` hook in React and how is it used?
`useContext` is a hook that allows you to access the value of a React context within a functional component, avoiding the need to pass props manually through the component tree.
18. How can you implement dynamic routing in React?
Dynamic routing in React can be implemented using `react-router-dom` by defining `Route` components with path parameters or query parameters and using `useParams` or `useLocation` hooks to access them.
19. What are controlled and uncontrolled components in React?
Controlled components are those where React state is used to manage the input values, whereas uncontrolled components manage their state internally using the DOM.
20. How can you pass data between sibling components in React?
Data between sibling components can be passed through a common parent component, which holds the state and passes it down to the children as props, or by using context for more complex scenarios.
21. What is the purpose of `React.memo`?
`React.memo` is a higher-order component that prevents unnecessary re-renders of a functional component by memoizing its output and re-rendering only when props change.
22. What are fragments in React, and why would you use them?
Fragments allow you to group a list of children without adding extra nodes to the DOM. They are useful when returning multiple elements from a component without wrapping them in a parent element.
23. How do you implement lazy loading in React?
Lazy loading in React can be implemented using `React.lazy()` to dynamically import components only when they are needed, often used with `Suspense` to display a loading indicator while the component is being loaded.
24. What is the `useLayoutEffect` hook in React?
`useLayoutEffect` is similar to `useEffect`, but it fires synchronously after all DOM mutations, making it useful for reading layout from the DOM and making updates before the browser paints.
25. What is the purpose of keys in lists in React?
Keys help React identify which items in a list have changed, been added, or been removed. They are important for optimizing rendering performance by minimizing re-renders.
26. How do you use refs in React?
Refs provide a way to access DOM nodes or React elements directly. You can create refs using `React.createRef()` for class components or `useRef()` for functional components.
27. What is the difference between `useState` and `useReducer`?
`useState` is used for managing simple state, while `useReducer` is ideal for more complex state logic, typically involving multiple sub-values or handling state transitions based on actions.
28. How does React’s reconciliation process work?
React’s reconciliation process compares the Virtual DOM with the actual DOM and computes the minimal set of changes required to update the actual DOM, improving performance.
29. What are compound components in React?
Compound components are components that work together by sharing state and behavior, allowing you to build more flexible and reusable components, often seen in form elements or UI libraries.
30. What is the significance of `dangerouslySetInnerHTML` in React?
`dangerouslySetInnerHTML` is used to set raw HTML content inside a component. It’s called “dangerous” because it exposes the app to cross-site scripting (XSS) attacks, and should be used with caution.
31. What is server-side rendering (SSR) in React?
Server-side rendering (SSR) is the process of rendering React components on the server, sending the fully rendered HTML to the client. This can improve initial load times and SEO.
32. What is the difference between `componentDidMount` and `useEffect`?
`componentDidMount` is a lifecycle method for class components that runs after the component has mounted. `useEffect` is a hook for functional components that can run after renders or be configured to run only once like `componentDidMount`.
33. How do you handle asynchronous operations in React?
Asynchronous operations can be handled using `useEffect` combined with `async`/`await` for data fetching, or by using Promises directly in event handlers and managing loading state.
34. What is the purpose of `useReducer` in React?
`useReducer` is a hook used for managing complex state logic. It is typically used when state depends on previous states or when you need to handle multiple sub-values in one state object.
35. What is JSX and how is it different from HTML?
JSX is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. It differs from HTML because it allows embedding expressions, JavaScript logic, and event handlers.
36. How can you prevent a component from re-rendering in React?
A component can be prevented from re-rendering by using `React.memo` for functional components or `shouldComponentUpdate` in class components. You can also use `useMemo` or `useCallback` to optimize performance.
37. How do you handle authentication in a React application?
Authentication in React is typically handled by maintaining a state or context to store the user’s authentication status and token, and using routing guards to prevent access to protected routes.
38. What are controlled and uncontrolled forms in React?
Controlled forms in React are those where form data is handled by React state. Uncontrolled forms let the DOM handle the form data and use refs to access the values.
39. What is `React.StrictMode` and how is it used?
`React.StrictMode` is a tool for highlighting potential problems in an application, like unsafe lifecycle methods, legacy API usage, or other common mistakes. It does not affect production builds.
40. How do you handle component state in a Redux store?
In Redux, component state is managed by dispatching actions to a store. A reducer listens for these actions and updates the store's state accordingly, allowing components to subscribe to the state.
41. What is the purpose of `useEffect` in React?
`useEffect` is used to perform side effects in functional components, such as fetching data, subscribing to external events, or directly manipulating the DOM after a render.
42. How can you share state between components in React?
State can be shared between components by lifting the state up to a common ancestor and passing it down as props, or by using React Context to provide global state.
43. How can you optimize the performance of a React application?
Performance can be optimized by using `React.memo` for functional components, `shouldComponentUpdate` in class components, lazy loading components, and reducing the number of re-renders.
44. What is the difference between `useEffect` and `useLayoutEffect`?
`useEffect` runs after the render and paint, while `useLayoutEffect` runs synchronously after all DOM mutations but before the paint, useful for layout calculations.
45. What are Higher-Order Components (HOCs) in React?
Higher-Order Components are functions that take a component and return a new component, allowing the reuse of component logic and behavior.
46. How can you handle form validation in React?
Form validation in React can be handled by controlling the form’s input state, using validation libraries like Formik or React Hook Form, or manually validating the data in an event handler.
47. What is the `useImperativeHandle` hook in React?
`useImperativeHandle` customizes the instance value that is exposed when using `ref` in functional components, allowing you to expose only specific methods or properties.
48. How do you implement dynamic imports in React?
Dynamic imports in React can be implemented using `React.lazy()` to import components only when they are needed, combined with `Suspense` to show a loading state during the import.
49. What is the context API in React?
The context API is used for sharing state or data across multiple components in the component tree without passing props down manually at every level.
50. What are the differences between functional and class components in React?
Functional components are simpler and use hooks for managing state and side effects, while class components use lifecycle methods and `this` to manage state and handle events.
51. What is the `useContext` hook used for?
The `useContext` hook allows you to consume values from a React context, making it easier to share global state across components without manually passing props.
52. How do you handle error boundaries in React?
Error boundaries are implemented as class components that use the `componentDidCatch` lifecycle method to catch JavaScript errors in their child components and display a fallback UI.
53. What is the role of `useCallback` in React?
`useCallback` is a hook that memoizes a function, preventing unnecessary re-creation of functions on every render, which helps in improving performance for components that rely on reference equality.
54. What is the difference between `useMemo` and `useCallback`?
`useMemo` memoizes the result of a computation (return value), while `useCallback` memoizes the function itself. Both help prevent unnecessary re-calculations and improve performance.
55. How do you handle side effects with `useEffect`?
Side effects with `useEffect` can be handled by performing actions such as fetching data, setting up event listeners, or manually updating the DOM after the render phase. Cleanup functions are also possible in `useEffect`.
56. What is the difference between `map` and `forEach` in JavaScript?
`map` returns a new array and is often used to transform elements, while `forEach` iterates over an array without returning a value, typically used for side effects.
57. What is `React.StrictMode` and how does it help developers?
`React.StrictMode` is a tool that helps developers identify potential problems in their React applications by highlighting deprecated API usage, unsafe lifecycle methods, and other issues in development.
58. How do you handle nested routes in React?
Nested routes can be handled using `react-router-dom` by creating routes within parent components. The child routes are rendered using `Route` components inside a `Switch` or `Routes` component.
59. How do you pass props to a component in React?
Props are passed to a component by including them as attributes in the JSX tag of the component, and can be accessed inside the component using `props` (in class components) or directly in function arguments (in functional components).
60. What is React's Virtual DOM?
The Virtual DOM is a lightweight copy of the actual DOM. React updates the Virtual DOM first, then calculates the minimal set of changes to apply to the actual DOM to optimize performance.
61. What is the `useRef` hook used for in React?
`useRef` is used to persist values across renders without causing re-renders. It can be used to access DOM elements or store mutable values that don't need to trigger a re-render.
62. How can you handle dynamic routing in React?
Dynamic routing in React can be achieved using `react-router-dom` by passing dynamic parameters in the route path (e.g., `/user/:id`) and accessing them via `useParams` hook or `match` object.
63. How do you conditionally render elements in React?
Conditional rendering in React can be done using JavaScript operators like `if`, `ternary`, or `&&` inside JSX to decide which component or element to display based on certain conditions.
64. What is the purpose of keys in React lists?
Keys are used in React to identify which items in the list are changed, added, or removed, helping React optimize the re-rendering process by improving the reconciliation algorithm.
65. How can you handle forms in React?
Forms in React can be handled by managing the state of form inputs using `useState`, and submitting the form by handling events like `onSubmit` and validating form data before submission.
66. What is a “controlled” component in React?
A controlled component is a form element where the React state controls the value of the input field, and the value is updated via state setters (e.g., `useState` hook) instead of directly modifying the DOM.
67. What are render props in React?
Render props are a pattern where a component receives a function as a prop, and this function is called to render dynamic content, allowing for greater reusability of components.
68. What is React Router and why is it important?
React Router is a library for handling routing in React applications, allowing navigation between views, handling dynamic URLs, and preserving application state across navigation without full page reloads.
69. What is the `useLayoutEffect` hook in React?
`useLayoutEffect` is similar to `useEffect`, but it runs synchronously after all DOM mutations. It is useful for reading or modifying the DOM before the browser repaints.
70. What is the purpose of `React.Fragment`?
`React.Fragment` is used to group multiple children elements without adding extra nodes to the DOM. It helps in returning multiple elements from a component without introducing unnecessary divs or wrappers.
71. How can you prevent unnecessary re-renders in React?
Unnecessary re-renders can be prevented by using `React.memo`, `shouldComponentUpdate`, and `useMemo` or `useCallback` hooks to memoize components or values, as well as optimizing state and props updates.
72. What is the purpose of `useState` in React?
`useState` is a React hook that allows functional components to manage and update local state. It returns an array with the current state value and a function to update it.
73. What is the difference between `componentDidMount` and `useEffect`?
`componentDidMount` is a lifecycle method in class components that runs once after the component mounts, while `useEffect` is a hook used in functional components to handle side effects and can be configured to run after mounting or on state/prop changes.
74. What is `React.memo` and how does it work?
`React.memo` is a higher-order component that memoizes a component, preventing re-renders unless its props change, optimizing performance for functional components.
75. How do you handle async operations in React?
Async operations in React can be handled using the `useEffect` hook or lifecycle methods in class components, along with promises or async/await syntax for handling data fetching, and updating state once the data is received.
76. What is a “stateless” component in React?
A stateless component is a component that does not manage any local state and simply receives props to render content. These are typically functional components.
77. How can you pass data from a child component to a parent component in React?
Data can be passed from a child component to a parent component using callbacks. The parent passes a function to the child as a prop, and the child invokes this function to send data back.
78. What is the `useReducer` hook in React?
The `useReducer` hook is used for managing more complex state logic in React, often replacing `useState` for handling state transitions based on actions, similar to how Redux works.
79. What are controlled components in React forms?
Controlled components in React are form elements whose value is controlled by React state, ensuring that input fields reflect and modify the state via event handlers such as `onChange`.
80. How do you implement pagination in React?
Pagination in React can be implemented by managing page state using `useState`, slicing the data array based on the current page, and rendering the data for the corresponding page.
81. What is the purpose of `useEffect` in React?
`useEffect` is a hook used for handling side effects in functional components. It allows you to perform tasks like fetching data, subscribing to external services, or directly manipulating the DOM.
82. What are prop types in React?
Prop types in React are used to validate the type and presence of props passed to components. This helps catch errors and ensures that components receive the expected data type for props.
83. How do you handle state in class components?
In class components, state is managed using `this.state` for storing the state and `this.setState` for updating the state. `this.setState` triggers a re-render of the component when the state changes.
84. What is the purpose of `React.createElement`?
`React.createElement` is a function used to create React elements, which are the building blocks of a React application. It is typically used internally by JSX to create elements based on the JSX syntax.
85. What is the significance of the `key` prop in React?
The `key` prop helps React identify which items in a list are changed, added, or removed, enabling efficient updates during re-renders by optimizing the reconciliation process.
86. How do you update the state of a functional component in React?
In functional components, state can be updated using the `useState` hook, which returns a state variable and a setter function. The setter function is used to update the state.
87. What are the differences between React components and HTML elements?
React components are custom, reusable building blocks that encapsulate logic and rendering behavior, whereas HTML elements represent static pieces of the DOM structure. React components are dynamic and can manage state and behavior.
88. What is a “higher-order component” (HOC) in React?
A higher-order component (HOC) is a function that takes a component and returns a new component with additional functionality or modifications, enabling component reuse and logic abstraction.
89. What is `useCallback` in React?
`useCallback` is a hook that memoizes a function and returns a memoized version of the callback function. This helps prevent unnecessary re-creations of functions during re-renders, optimizing performance.
90. How do you handle event binding in React?
In React, event handlers are typically bound using arrow functions or class method syntax. For class components, methods are often bound to the instance in the constructor using `.bind()`, while in functional components, arrow functions automatically bind the context.
81. What is the purpose of `useEffect` in React?
`useEffect` is a hook used for handling side effects in functional components. It allows you to perform tasks like fetching data, subscribing to external services, or directly manipulating the DOM.
82. What are prop types in React?
Prop types in React are used to validate the type and presence of props passed to components. This helps catch errors and ensures that components receive the expected data type for props.
83. How do you handle state in class components?
In class components, state is managed using `this.state` for storing the state and `this.setState` for updating the state. `this.setState` triggers a re-render of the component when the state changes.
84. What is the purpose of `React.createElement`?
`React.createElement` is a function used to create React elements, which are the building blocks of a React application. It is typically used internally by JSX to create elements based on the JSX syntax.
85. What is the significance of the `key` prop in React?
The `key` prop helps React identify which items in a list are changed, added, or removed, enabling efficient updates during re-renders by optimizing the reconciliation process.
86. How do you update the state of a functional component in React?
In functional components, state can be updated using the `useState` hook, which returns a state variable and a setter function. The setter function is used to update the state.
87. What are the differences between React components and HTML elements?
React components are custom, reusable building blocks that encapsulate logic and rendering behavior, whereas HTML elements represent static pieces of the DOM structure. React components are dynamic and can manage state and behavior.
88. What is a “higher-order component” (HOC) in React?
A higher-order component (HOC) is a function that takes a component and returns a new component with additional functionality or modifications, enabling component reuse and logic abstraction.
89. What is `useCallback` in React?
`useCallback` is a hook that memoizes a function and returns a memoized version of the callback function. This helps prevent unnecessary re-creations of functions during re-renders, optimizing performance.
90. How do you handle event binding in React?
In React, event handlers are typically bound using arrow functions or class method syntax. For class components, methods are often bound to the instance in the constructor using `.bind()`, while in functional components, arrow functions automatically bind the context.
91. What is the difference between `useMemo` and `useCallback`?
`useMemo` is used to memoize the result of a computation, while `useCallback` is used to memoize a function itself. `useMemo` helps prevent unnecessary recalculations, and `useCallback` prevents function recreation between renders.
92. What is the virtual DOM in React?
The virtual DOM is a lightweight JavaScript representation of the real DOM. React updates the virtual DOM first, compares changes using the diffing algorithm, and then updates only the necessary parts of the actual DOM.
93. How can you implement error boundaries in React?
Error boundaries are implemented using class components with lifecycle methods like `componentDidCatch` and `getDerivedStateFromError` to catch and handle errors in child components.
94. What is the difference between `useEffect` and `useLayoutEffect`?
`useEffect` runs asynchronously after rendering, while `useLayoutEffect` runs synchronously after all DOM mutations but before the browser paints. `useLayoutEffect` is useful for operations that require immediate DOM updates.
95. What is the purpose of the `defaultProps` property in React?
`defaultProps` allows you to set default values for props in case they are not provided when a component is rendered. This helps ensure components always have valid props.
96. How do you implement lazy loading in React?
Lazy loading in React is implemented using `React.lazy()` for dynamic component imports, and `Suspense` to display a fallback UI while the component is being loaded.
97. What is `StrictMode` in React?
`StrictMode` is a wrapper component that helps identify potential problems in an application by highlighting unsafe lifecycle methods, deprecated APIs, and unintended side effects in development mode.
98. How can you use environment variables in a React project?
Environment variables in React are stored in a `.env` file and can be accessed using `process.env.REACT_APP_
99. What are React portals?
React portals allow rendering a component outside of its parent DOM hierarchy while preserving its React context. This is useful for modals, tooltips, and pop-ups.
100. How can you optimize performance in a React application?
Performance optimization in React can be achieved using techniques like memoization (`useMemo`, `React.memo`), lazy loading, code splitting, efficient state management, avoiding unnecessary re-renders, and using the production build of React.
101. What is reconciliation in React?
Reconciliation is the process by which React updates the virtual DOM and efficiently determines the minimal changes needed to update the real DOM.
102. What are synthetic events in React?
Synthetic events are wrapper objects around native browser events that ensure consistent event handling across different browsers.
103. How can you dynamically import a component in React?
A component can be dynamically imported using `React.lazy(() => import('./Component'))`, which enables code splitting and improves performance.
104. What is `getDerivedStateFromProps`?
`getDerivedStateFromProps` is a static lifecycle method in class components that updates state based on changes in props before rendering.
105. How do you prevent a component from rendering?
A component can be prevented from rendering by returning `null` from its render method or using conditional rendering with state or props.
106. What is the difference between `React.Fragment` and div?
`React.Fragment` allows grouping multiple elements without adding an extra DOM node, while `div` adds an additional wrapper element in the DOM.
107. How does the `useRef` hook work?
`useRef` creates a mutable reference that persists across renders without triggering a re-render, often used for accessing DOM elements directly.
108. What is forwardRef in React?
`forwardRef` allows passing a ref from a parent component to a child component, enabling direct manipulation of the child’s DOM element.
109. How can you debounce a function in React?
A function can be debounced using libraries like Lodash’s `_.debounce()` or by implementing a custom debounce function with `setTimeout` and `clearTimeout`.
110. What is tree shaking in React applications?
Tree shaking is a technique used to remove unused JavaScript code during bundling, helping reduce the final bundle size and improving performance.
111. What is code splitting in React?
Code splitting is a technique used to break a large JavaScript bundle into smaller chunks that are loaded dynamically, improving performance and reducing initial load time.
112. How does `React.memo` improve performance?
`React.memo` is a higher-order component that prevents unnecessary re-renders by memoizing the rendered output of a component and only updating it when props change.
113. What is hydration in React?
Hydration is the process of attaching event listeners and state to server-rendered HTML to make it fully interactive on the client side.
114. How does `useReducer` differ from `useState`?
`useReducer` is an alternative to `useState` that is better suited for managing complex state logic involving multiple sub-values and actions, similar to Redux reducers.
115. What are controlled and uncontrolled components in React?
Controlled components are form inputs whose value is managed by React state, while uncontrolled components use refs to access input values directly.
116. What is suspense in React?
`Suspense` is a component used for handling asynchronous operations like code splitting and data fetching, allowing React to show a fallback UI while waiting.
117. How can you measure performance in a React application?
React performance can be measured using the React Developer Tools Profiler, Chrome DevTools, or by manually logging render times with `performance.now()`.
118. What is the difference between `props.children` and `React.cloneElement`?
`props.children` allows passing elements as children of a component, while `React.cloneElement` creates a new element with modified props or behavior.
119. What are hooks rules in React?
Hooks must only be called at the top level of a function component and not inside loops, conditions, or nested functions. They must also be used in React functional components or custom hooks.
120. What is the significance of the `displayName` property in React?
The `displayName` property is used to define a human-readable name for a component in debugging tools like React Developer Tools.
1. What is React Fiber?
React Fiber is the new reconciliation algorithm introduced in React 16 that improves rendering performance and enables features like concurrent mode, suspense, and priority-based updates.
2. How does concurrent mode work in React?
Concurrent Mode allows React to interrupt rendering tasks to prioritize important updates, making applications feel more responsive and reducing UI blocking.
3. What is the difference between React 17 and React 18?
React 18 introduces features like concurrent rendering, `useId`, automatic batching, and the new `startTransition` API, while React 17 focused on improving gradual adoption without breaking changes.
4. What are React server components?
React Server Components (RSC) allow components to be rendered on the server, reducing client-side JavaScript bundle size and improving performance by streaming UI updates.
5. How does React handle rendering priority?
React assigns different priority levels to updates using concurrent rendering. It uses mechanisms like `startTransition` for low-priority updates and `useDeferredValue` for delayed state updates.
6. What is React’s Diffing Algorithm?
React’s diffing algorithm, also known as the Reconciliation algorithm, efficiently updates the UI by comparing the virtual DOM with the previous state and applying minimal updates to the real DOM.
7. What is hydration in server-side rendering?
Hydration is the process where React attaches event listeners and client-side state to the pre-rendered HTML received from the server to make it fully interactive.
8. What is the role of `useDeferredValue`?
`useDeferredValue` helps manage UI responsiveness by deferring the update of a state value until higher-priority renders have completed, improving user experience in slow updates.
9. What is `useSyncExternalStore`?
`useSyncExternalStore` is a hook introduced in React 18 to efficiently subscribe to external data sources (e.g., Redux store) without unnecessary re-renders.
10. How do Suspense boundaries improve application performance?
Suspense boundaries allow React to pause rendering and show fallback UI while waiting for asynchronous operations, reducing UI flickering and improving perceived performance.
11. What is the `useTransition` hook in React?
`useTransition` is a React hook that allows marking certain state updates as non-urgent, helping prevent UI blocking by keeping the interface responsive.
12. What is the difference between `useTransition` and `startTransition`?
`useTransition` returns a state value indicating if a transition is pending, while `startTransition` is used to wrap low-priority updates inside an event handler.
13. How does React optimize large lists with virtualization?
React uses list virtualization libraries like `react-window` and `react-virtualized` to render only visible items in a large list, improving performance and reducing memory usage.
14. What are React hooks factories?
A hooks factory is a function that generates and returns a custom hook, allowing reusable logic while maintaining encapsulation.
15. What is React’s `unstable_useCacheRefresh` API?
`unstable_useCacheRefresh` is an experimental API in React for refreshing cache data without requiring a full re-render, mainly used for server components.
16. How does React handle memory leaks?
React prevents memory leaks by cleaning up event listeners, subscriptions, and timers inside `useEffect` using the cleanup function, and by correctly unmounting components.
17. What is the difference between `useMemo` and `useCallback`?
`useMemo` memoizes the result of an expensive computation, while `useCallback` memoizes the function reference to prevent unnecessary re-renders of child components.
18. How does `React.lazy` work with `Suspense`?
`React.lazy` enables dynamic imports of components, and `Suspense` wraps them to show a fallback UI while the component loads asynchronously.
19. What is progressive hydration?
Progressive hydration is a technique where React hydrates parts of a server-rendered application in stages rather than all at once, improving load time and interactivity.
20. How does React manage batching updates?
React batches multiple state updates into a single re-render to optimize performance. React 18 introduced automatic batching, which groups updates from different event handlers.
21. What is the role of `useImperativeHandle` in React?
`useImperativeHandle` allows customizing the instance value of a ref when using `forwardRef`, giving parent components more control over child component methods.
22. How does React’s `useDeferredValue` improve rendering performance?
`useDeferredValue` delays the update of a value until higher-priority updates finish, improving responsiveness by avoiding unnecessary re-renders.
23. What is the difference between React’s synthetic events and native events?
React synthetic events are wrapper objects around native browser events, providing cross-browser compatibility and optimized event pooling.
24. What is time slicing in React?
Time slicing is a React optimization where rendering work is split into smaller chunks, allowing the browser to remain responsive by interleaving rendering with user interactions.
25. How do you optimize performance in React applications?
React performance can be optimized using memoization (`useMemo`, `useCallback`), list virtualization, lazy loading, Suspense, and reducing unnecessary re-renders.
26. What is the purpose of the `Profiler` API in React?
The `Profiler` API helps measure component render times and identify performance bottlenecks by tracking how often components render and how long they take.
27. What is the difference between shallow and deep comparison in React state updates?
Shallow comparison checks only reference equality, while deep comparison checks nested object values. React uses shallow comparison for state updates to determine if a re-render is needed.
28. How does React handle reconciliation with keys in lists?
React uses keys to uniquely identify list items, optimizing reconciliation by minimizing unnecessary re-renders and improving the efficiency of updates.
29. What are React portals, and when should they be used?
React portals allow rendering a component’s children into a different part of the DOM, useful for modals, tooltips, and popups that need to break out of the parent hierarchy.
30. What is the `useId` hook introduced in React 18?
`useId` generates stable unique IDs for accessibility and server-side rendering, ensuring IDs do not clash between client and server-rendered content.
31. How does automatic batching improve performance in React 18?
Automatic batching groups multiple state updates into a single re-render, reducing unnecessary renders and improving performance.
32. What are React’s Transition APIs, and how do they work?
React’s Transition APIs (`useTransition` and `startTransition`) allow differentiating between urgent and non-urgent updates, improving responsiveness by deferring low-priority state updates.
33. What is the significance of React’s `act()` function in testing?
The `act()` function ensures that all updates related to an interaction (e.g., event handling, state updates) are properly applied before assertions in React tests.
34. How does React handle context propagation efficiently?
React optimizes context propagation by only re-rendering components that consume the context value, rather than re-rendering the entire tree.
35. What is React’s experimental `useMutableSource` hook?
`useMutableSource` was an experimental hook designed to efficiently subscribe to external mutable sources, but it has been replaced by `useSyncExternalStore` in React 18.
36. How does `useEffect` handle dependencies when using objects or arrays?
`useEffect` relies on reference equality, so objects and arrays should be memoized using `useMemo` or `useCallback` to avoid unnecessary re-renders.
37. What is the role of `useInsertionEffect` in React?
`useInsertionEffect` is a React hook introduced in React 18 that allows inserting styles into the DOM before layout effects and paints, optimizing performance for CSS-in-JS libraries.
38. How does `Suspense` help with code splitting?
`Suspense` defers rendering of components until their dependencies (e.g., lazy-loaded modules, fetched data) are ready, displaying fallback UI in the meantime.
39. What are React’s render phases?
React has two render phases: the **render phase**, where it calculates th
41. What is hydration in React?
Hydration is the process of attaching event listeners and state to server-rendered HTML, allowing the React application to become fully interactive.
42. What are React Server Components?
React Server Components (RSC) allow rendering components on the server, reducing client-side JavaScript and improving performance.
43. How does React optimize rendering performance with selective hydration?
Selective hydration prioritizes rendering and hydrating critical UI elements first while deferring non-essential components.
44. What are the key differences between SSR, CSR, and SSG in React?
- **SSR (Server-Side Rendering):** Renders pages on the server before sending them to the client.
- **CSR (Client-Side Rendering):** Loads an empty HTML shell and renders content using JavaScript.
- **SSG (Static Site Generation):** Generates static HTML pages at build time, improving performance.
45. How does React handle error boundaries?
Error boundaries are React components that catch JavaScript errors in child components and display fallback UI instead of crashing the application.
46. What is tree shaking in React applications?
Tree shaking is a technique used in modern bundlers to remove unused JavaScript code from production builds, reducing bundle size.
47. What is the role of Web Workers in React applications?
Web Workers allow running scripts in background threads, helping React applications handle expensive computations without blocking the main UI thread.
48. How does `useSyncExternalStore` improve state synchronization?
`useSyncExternalStore` ensures that external store updates (e.g., Redux state) remain consistent between server and client renders.
49. What is priority-based rendering in React?
Priority-based rendering allows React to prioritize certain updates over others, ensuring that critical UI updates render faster.
50. How does React’s concurrent mode improve performance?
Concurrent mode enables React to work on multiple tasks simultaneously, pausing low-priority updates and keeping the UI responsive.
51. What are React Fiber’s main advantages over the older reconciliation algorithm?
React Fiber improves rendering by enabling incremental rendering, prioritization, and pausing of updates, making UI updates smoother.
52. How does `useLayoutEffect` differ from `useEffect`?
`useLayoutEffect` fires synchronously after DOM mutations but before the browser repaints, whereas `useEffect` runs asynchronously after rendering.
53. What is suspense streaming in React?
Suspense streaming enables sending parts of a page to the client as they become available, improving perceived performance for large applications.
54. How do you prevent unnecessary context re-renders in React?
Use memoization (`React.memo`, `useMemo`), split context providers, and avoid passing objects/functions directly to context values.
55. What is the `unstable_useTransition` hook used for?
`unstable_useTransition` (now `useTransition`) is used for marking updates as non-urgent, preventing UI blocking and improving performance.
56. How do you debug React performance issues?
Use the React DevTools Profiler, measure render times with `Profiler` API, and analyze component re-renders with logging or memoization.
57. What is the purpose of `React.forwardRef`?
`React.forwardRef` allows passing refs from a parent component to a child, enabling direct manipulation of child DOM elements or components.
58. How does React optimize large list rendering?
React optimizes large lists with virtualization techniques using libraries like `react-window` or `react-virtualized`, rendering only visible items.
59. What is hydration mismatching in React?
Hydration mismatching occurs when the server-rendered HTML differs from the client-rendered output, leading to UI inconsistencies.
60. What are module federation and micro-frontends in React?
Module federation allows splitting large applications into smaller, independently deployable micro-frontends that share dependencies dynamically.
61. How does React’s concurrent rendering improve user experience?
Concurrent rendering enables React to prioritize urgent updates while pausing non-urgent ones, leading to smoother and faster UI responses.
62. What is the significance of `React.lazy` and `Suspense`?
`React.lazy` enables code-splitting by dynamically importing components, while `Suspense` provides fallback UI while waiting for the components to load.
63. How do you implement a global state management system using React?
Use context API along with `useReducer` for complex state logic or a third-party library like Redux, Recoil, or Zustand for better scalability.
64. What are “controlled” and “uncontrolled” components in React?
Controlled components are those whose value is controlled by React state, while uncontrolled components store their own value in the DOM.
65. How does React handle form validation efficiently?
React handles form validation through controlled components with event handlers, validating fields on change, submit, or blur events.
66. What are hooks rules in React?
Hooks must be called at the top level of a function component or custom hook, and only within function components or other hooks.
67. How do you handle state changes across multiple components in React?
Use lifting state up to a common ancestor or leverage global state solutions like Context API, Redux, or Zustand for cross-component state management.
68. What is the difference between React’s `useMemo` and `useCallback` hooks?
`useMemo` memoizes values to avoid unnecessary calculations, while `useCallback` memoizes functions to prevent re-creating them on every render.
69. What is a “render prop” pattern in React?
The render prop pattern involves passing a function as a prop to a component, which renders UI based on internal state or logic.
70. How do you handle side effects in React components?
Use the `useEffect` hook to handle side effects like fetching data, interacting with the DOM, or subscribing to external data sources.
71. What is the purpose of `React.memo`?
`React.memo` is used to memoize functional components, preventing unnecessary re-renders if props haven't changed.
72. What is a higher-order component (HOC) in React?
A higher-order component is a function that takes a component and returns a new component, enhancing the original one with additional functionality.
73. How can you manage side effects when working with asynchronous code in React?
Use `useEffect` for handling side effects with asynchronous code. For API calls, ensure that the effect cleans up when the component unmounts to avoid memory leaks.
74. How can you improve the performance of React applications?
Use memoization techniques (`React.memo`, `useMemo`, `useCallback`), code-splitting, lazy loading, virtualization of large lists, and efficient state management to optimize performance.
75. What is the significance of React’s Context API?
The Context API provides a way to share state across the component tree without prop drilling, making it easier to manage global state in a React app.
76. How do you implement error boundaries in React?
Error boundaries are implemented by creating components that catch JavaScript errors during rendering and lifecycle methods, displaying a fallback UI.
77. What are the benefits of using TypeScript with React?
TypeScript improves type safety, enhances code completion, and helps detect bugs earlier by providing static typing and better tooling in React applications.
78. How does React handle performance optimizations in large-scale applications?
React uses techniques like shouldComponentUpdate, React.memo, lazy loading, and code-splitting to optimize performance in large applications.
79. What is the difference between `useRef` and `createRef`?
`useRef` is used in function components to persist values across renders without causing re-renders, while `createRef` is used in class components.
80. How do you handle code-splitting in React?
Code-splitting can be done using `React.lazy` and `Suspense`, dynamically loading components only when needed, reducing the initial bundle size.
81. What are React Portals and how are they used?
React Portals provide a way to render children into a DOM node outside the parent component hierarchy, useful for modals or tooltips.
82. What is the purpose of `React.Fragment`?
`React.Fragment` is used to group multiple elements without adding extra nodes to the DOM, improving performance and readability.
83. How does React’s context API handle performance issues?
To mitigate performance issues, avoid overusing Context API for large datasets and opt for memoization techniques like `useMemo` and `React.memo`.
84. How does React manage the virtual DOM?
React creates a virtual DOM, which is a lightweight in-memory representation of the actual DOM, and uses a diffing algorithm to efficiently update the real DOM.
85. What are synthetic events in React?
Synthetic events are React’s normalized version of browser events, providing consistent behavior across different browsers and handling events efficiently.
86. How can you achieve dynamic routing in React?
Dynamic routing in React can be achieved using libraries like `React Router`, where routes and components are mapped based on application state.
87. What is the difference between `componentDidMount` and `useEffect`?
`componentDidMount` is a class component lifecycle method for running side effects after the component mounts, while `useEffect` serves a similar purpose in function components.
88. What are React's best practices for performance optimization?
Best practices include avoiding unnecessary re-renders, using memoization, code splitting, lazy loading, and optimizing images and assets.
89. How do you handle concurrent rendering in React?
Concurrent rendering allows React to pause and resume rendering work, using features like `useTransition` and `Suspense` to manage non-urgent updates.
90. How do you test React components effectively?
Use testing libraries like `Jest` and `React Testing Library` to write unit and integration tests, mock API calls, and ensure components behave as expected.
91. How does React handle reconciliation?
React uses the reconciliation algorithm to compare the previous virtual DOM with the new one and updates the real DOM efficiently by minimizing changes.
92. How do you implement lazy loading of routes in React?
Lazy loading of routes in React can be done using `React.lazy` combined with `Suspense`, allowing components to load only when needed.
93. What is the use of the `useReducer` hook?
`useReducer` is used for managing more complex state logic in function components, offering a more predictable way of handling state changes compared to `useState`.
94. What is the purpose of the `useImperativeHandle` hook?
`useImperativeHandle` is used in function components to customize the instance value that is exposed to parent components when using `ref`.
95. What is the `useContext` hook used for?
The `useContext` hook is used to access values from the context without needing to explicitly pass props down the component tree.
96. What is the difference between `state` and `props` in React?
`State` represents data managed by the component, while `props` are data passed from parent to child components that cannot be modified by the child.
97. What are React Suspense boundaries and how do they work?
Suspense boundaries allow components to "wait" for something (like data or lazy-loaded components) before rendering, showing a fallback UI in the meantime.
98. How does React handle updating the DOM when multiple state changes occur?
React batches state updates and updates the DOM only after all state changes have been processed, which optimizes re-renders and improves performance.
99. How do you avoid memory leaks in React components?
To avoid memory leaks, clean up subscriptions, timers, or event listeners inside `useEffect`'s cleanup function when the component unmounts.
100. What is the role of keys in React lists?
Keys help React identify which items in the list are changed, added, or removed, optimizing the rendering and preventing unnecessary re-renders.
101. What are render props in React?
Render props is a pattern where a component takes a function as a prop and uses it to dynamically decide what to render, enabling component reuse.
102. How can you pass a ref to a child component in React?
You can use `forwardRef` to pass a `ref` from a parent component to a child component, allowing the child to directly access the DOM node.
103. What is React’s `useLayoutEffect` hook and how does it differ from `useEffect`?
`useLayoutEffect` runs synchronously after DOM mutations, while `useEffect` runs asynchronously after rendering. It's useful for reading layout and making DOM mutations.
104. What is the purpose of `React.createContext`?
`React.createContext` is used to create a Context object that provides a way to pass data through the component tree without having to manually pass props down each level.
105. How do you handle infinite scrolling in React?
Infinite scrolling can be implemented by listening to scroll events and loading more data when the user scrolls to the bottom of the page. You can use libraries like `react-infinite-scroll-component` for easier implementation.
106. What is the significance of the `useEffect` dependency array?
The dependency array of `useEffect` defines when the effect should run. If the dependencies change, the effect runs again. If it's empty, the effect runs only once after the initial render.
107. What is an `Error Boundary` in React and how does it work?
An `Error Boundary` is a React component that catches JavaScript errors anywhere in its child component tree, logs the errors, and displays a fallback UI instead of crashing the app.
108. How do you implement server-side rendering (SSR) in React?
SSR in React is implemented by rendering the React components on the server, sending the fully rendered HTML to the client, and allowing React to take over once the page loads. Tools like Next.js simplify SSR.
109. What is React’s `StrictMode` and when should you use it?
`StrictMode` is a wrapper component that helps identify potential problems in an application, like unsafe lifecycle methods and deprecated APIs. It's useful during development to improve code quality.
110. How does React handle reconciliation in the context of list rendering?
React uses a key property in lists to efficiently reconcile changes. It compares keys from the old and new virtual DOM and reorders or updates elements only when necessary.
111. What is the purpose of `React.memo`?
`React.memo` is a higher-order component that memoizes the rendering of a component, preventing unnecessary re-renders when the props have not changed.
112. What are higher-order components (HOCs) in React?
HOCs are functions that take a component and return a new component with additional props or behavior. They allow for reusable logic across components.
113. What is a "controlled component" in React?
A controlled component is a component whose value is controlled by React state, with changes triggered via `onChange` event handlers.
114. How do you optimize performance with large React applications?
Performance can be optimized by using lazy loading, code splitting, memoization, `React.memo`, avoiding unnecessary re-renders, and optimizing state management.
115. What is the significance of the `key` prop in React?
The `key` prop is used in lists to uniquely identify each element, which helps React efficiently update and reconcile the DOM during re-renders.
116. How do you handle state management in large-scale React applications?
State management in large apps can be handled using tools like Redux, MobX, or React Context API, based on the complexity of the state and the need for global state management.
117. How does React handle component lifecycle in functional components?
React handles component lifecycle in functional components through hooks like `useEffect`, `useLayoutEffect`, and `useState`, replacing lifecycle methods in class components.
118. What is `React.lazy` and how does it work?
`React.lazy` is a function that allows you to dynamically import components, enabling code splitting and lazy loading of components when they are needed.
119. What is the difference between `React.Component` and `React.PureComponent`?
`React.PureComponent` automatically implements `shouldComponentUpdate` with a shallow prop and state comparison, preventing unnecessary re-renders. `React.Component` does not include this optimization.
120. How do you prevent unnecessary re-renders in React?
Unnecessary re-renders can be prevented by using `React.memo`, `useMemo`, `useCallback`, and by ensuring components only update when necessary using `shouldComponentUpdate` or hooks like `useEffect` with proper dependencies.