React
React
Answer: React Hooks are functions that let you use state and other React features in functional
components. They were introduced to allow functional components to manage state and side
effects, promoting code reusability and reducing the need for class components.
Answer: The useEffect Hook allows you to perform side effects in functional components,
such as fetching data or subscribing to events. The dependencies array determines when the
effect runs:
3. What is the Context API, and when would you use it?
Answer: The Context API is a React feature that allows you to share state across components
without passing props manually through every level of the tree. It's useful for global state
management, theming, and avoiding prop drilling.
4. What are render props, and how do they differ from higher-order
components (HOCs)?
Answer: Render props is a technique for sharing code between React components using a
prop whose value is a function. Unlike HOCs, which wrap a component to enhance it, render
props directly pass data to a component as a function, providing more flexibility and control.
Answer: Lifting state up involves moving state to a common ancestor of components that need
to share that state. This allows for a single source of truth and ensures that both components
can access and update the shared state.
7. What is React's reconciliation process?
Answer: React's reconciliation process is how it updates the DOM efficiently. React creates a
virtual DOM to represent the UI. When a component's state or props change, React computes
the differences between the new virtual DOM and the previous one, then updates the real DOM
only for the changed elements, optimizing rendering performance.
Answer: The key prop helps React identify which items have changed, been added, or
removed in lists. It should be unique among siblings to ensure efficient updates and minimize
re-renders. Using stable identifiers (like IDs) is recommended over array indices.
Answer: Error boundaries are React components that catch JavaScript errors in their child
components' render methods, lifecycle methods, and constructors. They allow you to display a
fallback UI instead of crashing the whole app. Error boundaries are defined using class
components with a componentDidCatch lifecycle method.
Answer: In React, controlled components are form elements whose value is managed by React
state. You provide a value and an onChange handler, allowing React to control the form state.
This approach helps keep the UI in sync with the component state.
12. Explain the concept of Suspense and how it works with data fetching.
Answer: Suspense is a React feature that allows you to "wait" for some code or data to load
before rendering a component. It works with lazy loading of components and can also be used
with libraries like React Query for data fetching. It provides a fallback UI while waiting for the
data or component to become available
13. What is the significance of useReducer and when would you use it?
Answer: useReducer is a Hook that manages complex state logic in functional components,
especially when the state depends on previous states or when you have multiple state values. It
is often preferable to useState when managing forms, handling complex state transitions, or
working with large state objects.
Answer: Code splitting can be implemented using [Link] and Suspense. By wrapping
dynamically imported components with [Link], React can load them only when needed,
reducing the initial load time. Here’s an example:
Example:
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
Answer: Higher-order components are functions that take a component and return a new
component, enhancing it with additional props or functionality. HOCs are used for cross-cutting
concerns like logging, authentication, or data fetching. They help in reusing component logic.
16. What are some common patterns for managing side effects in React?
Answer: Controlled components are those where form data is handled by the component’s
state, while uncontrolled components manage their own state internally. Controlled components
provide more control over form data, while uncontrolled components are simpler but less
predictable.
Answer: The key prop is crucial for helping React identify which items in a list have changed,
been added, or removed. This allows for efficient updates, minimizing unnecessary re-renders
and improving performance. It should be a stable and unique identifier, not the index of the
array.
20. What are React portals, and how do you use them?
Answer: React portals provide a way to render a child component into a different part of the
DOM tree outside of its parent component. They are useful for modals or tooltips. You can
create a portal using [Link](child, container).
21. How do you handle context in React, and what are the performance
implications?
Answer: You can handle context using the Context API, creating a context object with
[Link](), and using [Link] to pass down the value.
Performance implications include potential re-renders of all consumers when context changes;
to mitigate this, you can split context into multiple providers or memoize values.
● Unit Testing: Using libraries like Jest and React Testing Library to test components in
isolation.
● Integration Testing: Testing how components work together.
● End-to-End Testing: Using tools like Cypress to simulate user interactions and ensure
the app behaves as expected.
Answer: Server-side rendering (SSR) is the process of rendering a React application on the
server rather than in the browser. It improves initial load performance and SEO, as the fully
rendered HTML is sent to the client, allowing for faster content display and better indexing by
search engines.
Answer: React creates a synthetic event system that normalizes browser event behavior to
provide consistent event handling across different browsers. Synthetic events are pooled,
meaning that they are reused for performance, so properties are accessible only within the
event handler.
26. What are the different lifecycle methods in React class components?
Answer: React batches state updates for performance. When a state update is made, React
schedules a re-render. If multiple state updates occur within the same event handler, React
processes them in a single pass, improving performance. To force immediate updates, you can
use flushSync from the React DOM.
Answer: useLayoutEffect is similar to useEffect, but it runs synchronously after all DOM
mutations. It’s useful for measuring DOM nodes and performing operations that need to be
completed before the browser paints (e.g., animations, layout calculations).
29. What are fragments in React, and why would you use them?
Answer: Fragments are a way to group multiple elements without adding extra nodes to the
DOM. They can be created using <[Link]> or the shorthand <>...</>. Fragments
help keep the DOM cleaner and avoid unnecessary wrappers.
Answer: Shallow comparison checks if the references of two objects are the same, while deep
comparison checks if the actual content of the objects is the same. React uses shallow
comparison in PureComponent and [Link], which can lead to performance
optimizations by preventing unnecessary re-renders.
Answer: React reconciliation is the process of updating the DOM efficiently. When a
component’s state or props change, React creates a new virtual DOM tree and compares it with
the previous tree using the diffing algorithm. It identifies changes and updates only the parts of
the actual DOM that have changed. This minimizes the number of direct DOM manipulations,
which are typically expensive in terms of performance.
36. How can you implement lazy loading for images in a React application?
Answer: Lazy loading for images can be implemented using the loading attribute in the
<img> tag, setting it to "lazy", or using libraries like react-lazyload. This defers loading
images until they are in the viewport, improving performance.
38. Explain the concept of suspense and how it relates to code splitting and
data fetching.
Answer: Suspense allows components to "wait" for something before rendering. It works well
with lazy-loaded components (code splitting) and data fetching libraries. When a component
wrapped in Suspense is loading, a fallback UI can be displayed until it’s ready, providing a
better user experience.
Answer: TypeScript provides static type checking, which can catch errors at compile time rather
than runtime, enhancing code quality. It improves IDE support with better autocompletion and
navigation, making it easier to work in larger codebases and collaborate in teams.
Answer: React batches state updates inside event handlers but may not batch updates in
asynchronous functions or promises. To handle async updates correctly, you may need to use
functional updates in setState or use useReducer for more complex state logic.
Answer: useDebugValue is a Hook that allows you to display a label in React DevTools for
custom Hooks. It helps developers understand the state of custom Hooks during debugging,
providing context about what values are being used.
Answer: Custom Hooks are JavaScript functions that start with use and allow you to
encapsulate and reuse stateful logic. They enable you to extract component logic into reusable
functions, promoting code organization and DRY (Don't Repeat Yourself) principles.
Answer: Side effects in functional components are typically managed using the useEffect
Hook. This Hook allows you to perform operations like data fetching, subscriptions, or manually
manipulating the DOM, and it cleans up after itself with return functions.
Answer: Focus management can be handled using refs to directly access DOM elements. You
can set focus in useEffect after a component mounts or updates. For example, using
[Link]() to programmatically manage focus based on user interactions or
conditions.
Answer: [Link] is used for dynamically importing components, allowing you to split code
at the component level. It returns a React component that loads the specified module only when
it is rendered, improving performance by reducing the initial bundle size.
49. Explain the concept of prop drilling and how to avoid it.
Answer: Prop drilling occurs when you pass data through multiple layers of components that do
not need it, making the code harder to maintain. To avoid prop drilling, you can use the Context
API, Redux, or Recoil for state management, allowing components to access global state
without intermediate props.
Answer: Uncontrolled components manage their own state internally, which can lead to
potential issues like:
Answer: In concurrent mode, React can work on multiple tasks at once, pausing and resuming
tasks to improve UI responsiveness. It prioritizes rendering updates based on user interactions,
enabling features like transitions and suspense without blocking the main thread.
Answer: In React Native, keyExtractor is a function used in lists (like FlatList) to provide a
unique key for each item. It helps React identify which items have changed, are added, or are
removed, improving performance during re-renders.
53. How can you implement authentication in a React application?
54. What are controlled and uncontrolled inputs, and when would you use
each?
Answer: Controlled inputs have their value controlled by React state, providing full control over
form data. Uncontrolled inputs manage their own state, which can simplify certain scenarios.
Use controlled inputs for complex forms and validation; use uncontrolled inputs for simple forms
or when integrating with non-React libraries.
55. What are React's error boundaries, and how do they differ from regular
error handling?
Answer: Error boundaries are components that catch JavaScript errors in their child
components, allowing you to display a fallback UI instead of crashing the whole app. Unlike
regular error handling, they handle errors during rendering and lifecycle methods, providing a
structured way to manage component errors.
fetchData();
}, [url]);
return { data, error, loading };
};
Answer: useContext is a Hook that allows you to access the value of a Context directly in a
functional component without needing to use the [Link] wrapper. You call it with
the Context object created by [Link](), and it returns the current context
value.
Answer: The strict mode in React enables additional checks and warnings for its
descendants, helping developers identify potential problems. It activates checks for deprecated
APIs, verifies that components are pure, and highlights potential side effects in the render
method.
Answer: componentDidMount is a lifecycle method in class components that runs once after
the component is mounted. In contrast, useEffect is a Hook in functional components that
can run after every render or based on specified dependencies, making it more flexible for
managing side effects.
Answer: A modal component can be created using React portals to render the modal outside of
the main DOM hierarchy. It typically includes state management for visibility and event handlers
to open and close the modal. Example:
Example
import ReactDOM from 'react-dom';
const Modal = ({ isOpen, onClose }) => {
if (!isOpen) return null;
return [Link](
<div className="modal">
<button onClick={onClose}>Close</button>
{/* Modal content */}
</div>,
[Link]('modal-root')
);
};
63. What are the different ways to fetch data in a React application?
Answer: A debounce function limits the rate at which a function can be invoked. You can
implement it using setTimeout in useEffect:
Example
import { useEffect, useState } from 'react';
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
65. What are the potential drawbacks of using index as a key in lists?
Answer: Using index as a key can lead to performance issues and incorrect UI behavior,
especially when items are reordered, added, or removed. It can cause React to incorrectly
match components with their keys, leading to unexpected behavior, such as retaining state in
components that should be recreated.
Answer: Service workers can be integrated into a React application using libraries like Workbox
or through Create React App, which includes a service worker by default. Service workers
enable features like caching, offline support, and background sync, enhancing performance and
user experience.
Answer: Nested routes in React Router can be defined by rendering child <Route>
components within a parent route. This allows for a hierarchical routing structure where child
components can access parent route data and rendering logic. Example:
javascript
Copy code
<Route path="/parent" element={<Parent />}>
<Route path="child" element={<Child />} />
</Route>
69. How can you implement pagination in a React application?
70. What are the benefits of using CSS Modules in a React application?
72. What is the difference between static and instance methods in class
components?
Answer: Static methods belong to the class itself and can be called without creating an
instance of the class, while instance methods require an object instance to be called. Static
methods are often used for utility functions, while instance methods manipulate the instance’s
state and behavior.
Answer: Controlled components have their form data managed by React state, allowing for
validation and state synchronization. Uncontrolled components manage their own internal state,
which can lead to simpler implementations but less control over form data and behavior.
Answer: Environment variables can be managed using .env files. Variables must start with
REACT_APP_ to be accessible in the application. You can use
[Link].REACT_APP_YOUR_VARIABLE to access them in your code, making it easy to
manage configuration settings for different environments.
Answer: combineReducers is a utility function in Redux that combines multiple reducers into
a single reducer function. This allows you to manage different parts of the state tree with
separate reducer functions, improving code organization and maintainability.
Answer: [Link] creates a Context object that allows for sharing values (like
state or functions) between components without passing props down manually at every level. It
provides a way to manage global state in a more straightforward manner, especially for deeply
nested components.
return state;
}
};
const [state, dispatch] = useReducer(reducer, initialState);
Answer: The key prop is a special attribute used in lists to help React identify which items have
changed, been added, or removed. It is crucial for efficient updates because it allows React to
optimize re-renders and maintain the internal component state correctly.
84. How do you handle component libraries in a React application?
Answer: "Lifting state up" refers to the practice of moving state management to a common
ancestor component to enable sibling components to share state. This ensures that data flows
down through props, maintaining a unidirectional data flow in the application.
Answer: contextType is used to subscribe a class component to a React context. You can
set contextType to the context object created by [Link](), allowing you to
access the context value via [Link].
Example:
javascript
Copy code
render() {
const value = [Link];
return <div>{value}</div>;
}
}
88. How do you create a responsive navigation menu in React?
Example:
javascript
// In the render
<nav>
<button onClick={toggleMenu}>Menu</button>
{isOpen && <ul>{/* Menu items */}</ul>}
</nav>
91. Explain how you can use useReducer for form management.
Answer: useReducer can manage complex form state by encapsulating the form's state and
validation logic in a reducer. Each input change can dispatch an action to update the state
accordingly, enabling better organization of form handling.
Example:
javascript
Copy code
Answer: Errors in asynchronous code can be managed using try/catch blocks with
async/await or using .catch() with Promises. In functional components, you can set error
state to handle UI updates based on errors.
javascript
Copy code
94. How can you implement accessibility (a11y) best practices in React?
Answer: Dynamic imports can be handled using [Link] for code splitting. This allows
you to load components only when needed, enhancing performance.
Example:
javascrip
// In the render
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
96. Explain how to use the useForm Hook from React Hook Form.
Answer: The useForm Hook from React Hook Form simplifies form handling by providing
methods to register inputs, handle submission, and manage validation.
Example:
Answer: A custom hook is a function that uses one or more React hooks to encapsulate
reusable logic. It must start with use and can return any value(s) needed.
Example:
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(url);
const result = await [Link]();
setData(result);
};
fetchData();
}, [url]);
return data;
}
Answer: A Provider in the Context API is a component that makes the context value available
to its child components. It wraps around the components that need access to the context and
takes a value prop that provides the current context value