React Intermediate Questions - Set 1

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.

React Intermediate Questions - Set 2

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.

 

React Intermediate Questions - Set 3

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.

 

React Intermediate Questions - Set 4

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.

React Intermediate Questions - Set 5

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.

 

React Intermediate Questions - Set 6

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.

 

React Intermediate Questions - Set 7

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.

 

React Intermediate Questions - Set 8

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.

 

React Intermediate Questions - Set 9

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.

React Intermediate Questions - Set 9

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.

React Intermediate Questions - Set 10

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_ `. They must start with `REACT_APP_` to be available in the client-side code.

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.

 

React Intermediate Questions - Set 11

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.

 

React Intermediate Questions - Set 12

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.