0% found this document useful (0 votes)
18 views22 pages

React

The document provides an extensive overview of React concepts, including React Hooks, the Context API, performance optimization techniques, and state management strategies. It covers various topics such as the useEffect Hook, error boundaries, controlled vs. uncontrolled components, and the reconciliation process. Additionally, it discusses testing strategies, server-side rendering, and the benefits of using TypeScript with React.

Uploaded by

Satish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views22 pages

React

The document provides an extensive overview of React concepts, including React Hooks, the Context API, performance optimization techniques, and state management strategies. It covers various topics such as the useEffect Hook, error boundaries, controlled vs. uncontrolled components, and the reconciliation process. Additionally, it discusses testing strategies, server-side rendering, and the benefits of using TypeScript with React.

Uploaded by

Satish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. What are React Hooks, and why were they introduced?

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.

2. Explain the useEffect Hook and its dependencies array.

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:

● If empty ([]), it runs once after the initial render.


● If it contains variables, the effect runs whenever those variables change.

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.

5. How do you optimize performance in a React application?

Answer: Performance can be optimized by:

● Using [Link] to prevent unnecessary re-renders of functional components.


● Implementing shouldComponentUpdate in class components.
● Leveraging lazy loading with [Link] and Suspense.
● Using code-splitting and tree-shaking to reduce bundle size.
● Memoizing expensive calculations with useMemo and useCallback.

6. Describe the concept of "lifting state up."

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.

8. What is the purpose of the key prop in lists?

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.

9. Explain how error boundaries work in React.

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.

10. What is the purpose of [Link]?

Answer: [Link] is a tool for highlighting potential problems in an application. It


activates additional checks and warnings for its descendants, such as identifying deprecated
lifecycle methods, ensuring components adhere to best practices, and detecting side effects that
may cause issues.

11. How does React handle forms and controlled components?

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.

14. How do you implement code splitting in a React application?

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:

const LazyComponent = [Link](() => import('./LazyComponent'));

<Suspense fallback={<div>Loading...</div>}>

<LazyComponent />

</Suspense>

15. Explain the concept of higher-order components (HOCs).

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: Common patterns for managing side effects include:

● Using useEffect for effects related to lifecycle events.


● Custom Hooks for encapsulating side effect logic that can be reused across
components.
● Libraries like Redux-Saga or Redux-Thunk for complex side effects in applications using
Redux.

17. How can you implement memoization in React?

Answer: Memoization can be implemented using useMemo and useCallback Hooks:

● useMemo is used to memoize the result of a computation to avoid recalculating it on


every render.
● useCallback is used to memoize functions, preventing unnecessary re-renders of child
components that depend on those functions.
18. What is the difference between controlled and uncontrolled
components?

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.

19. Explain the significance of React’s key prop in lists.

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.

22. What are some strategies for testing React components?

Answer: Strategies for testing React components include:

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

23. Describe the purpose and usage of [Link].


Answer: [Link] is a function that allows you to pass refs through a component
to one of its children. It’s useful for creating higher-order components that need access to the
child’s DOM node, enabling ref forwarding without altering the component’s API.

24. What is server-side rendering (SSR) in React, and why is it useful?

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.

25. How does React handle synthetic events?

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: The main lifecycle methods in React class components include:

● constructor(): Initializes state and binds methods.


● componentDidMount(): Called after the component is mounted; ideal for data
fetching.
● componentDidUpdate(): Invoked after updates; useful for responding to prop or state
changes.
● componentWillUnmount(): Cleanup tasks before the component is removed.
● shouldComponentUpdate(): Determines whether the component should re-render
based on prop/state changes.

27. How does React handle state updates?

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.

28. What is the significance of the useLayoutEffect Hook?

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.

30. How can you optimize re-renders in functional components?

Answer: To optimize re-renders in functional components:

● Use [Link] to prevent re-renders when props haven't changed.


● Memoize expensive calculations with useMemo.
● Use useCallback to memoize functions passed as props.
● Split components to minimize the re-rendering scope.

31. Explain the difference between shallow comparison and deep


comparison in React.

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.

32. What is the purpose of [Link]?

Answer: [Link] is a higher-order component that memoizes functional components. It


prevents a component from re-rendering if its props haven't changed, optimizing performance
for components that receive the same props frequently.

33. How do you manage global state in a React application?

Answer: Global state can be managed using:

● Context API: For simple global state management.


● Redux: A state management library that provides a predictable state container for
complex applications.
● Recoil: A state management library for React that provides a more flexible and
fine-grained approach than Redux.
● MobX: Another state management library that leverages observable states.

34. What is the difference between useMemo and useCallback?


Answer: useMemo returns a memoized value of a computed function, while useCallback
returns a memoized version of the callback function itself. Both Hooks help prevent
unnecessary calculations or function re-creations on re-renders.

35. Describe the concept of "React reconciliation" in detail.

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.

37. What is the use of [Link] in development?

Answer: [Link] is a development tool that helps identify potential problems in an


application. It activates checks for deprecated APIs, ensures components are pure, and
highlights side effects in render methods. It does not affect production builds.

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.

39. What are the benefits of using TypeScript with React?

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.

40. How do you handle form validation in React?

Answer: Form validation can be handled in various ways:

● Manual validation in onChange or onSubmit handlers.


● Using controlled components to manage form state.
● Libraries like Formik or React Hook Form, which simplify form handling and validation.

41. What is the role of useImperativeHandle?

Answer: useImperativeHandle is a Hook that customizes the instance value that is


exposed when using ref in functional components. It allows you to control what functions or
properties are accessible to parent components, often used with [Link].

42. How does React handle asynchronous state updates?

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.

43. What is the purpose of the useDebugValue Hook?

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.

44. Explain the concept of custom Hooks.

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.

45. How do you manage side effects in functional components?

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.

46. What are the advantages of using React Router?

Answer: React Router provides declarative routing in React applications. It enables:

● Nested routing for complex UIs.


● Dynamic routing based on application state.
● Code splitting and lazy loading for route components.
● A simple API for handling navigation and route transitions.

47. How can you handle focus management in React?

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.

48. What is the purpose of [Link]?

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.

50. What are the potential issues with uncontrolled components?

Answer: Uncontrolled components manage their own state internally, which can lead to
potential issues like:

● Difficulty in synchronizing state with the component’s behavior.


● Challenges in performing validation or manipulating values before submission.
● Limited control over form data as it is not bound to component state.

51. How does React handle updates in concurrent mode?

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.

52. What is the keyExtractor in React Native?

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?

Answer: Authentication can be implemented using:

● Context API to manage user state globally.


● Libraries like Firebase or Auth0 for authentication services.
● Routing protection to restrict access to certain routes based on user authentication state.

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.

56. How can you create a custom useFetch Hook?


import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (![Link]) throw new Error('Network response was not ok');
const result = await [Link]();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};

fetchData();
}, [url]);
return { data, error, loading };
};

57. What is useContext, and how do you use it?

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.

58. What is the significance of the strict mode in React?

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.

59. How do you handle data synchronization in React applications?

Answer: Data synchronization can be managed using:

● State management libraries (like Redux or MobX).


● WebSocket for real-time updates.
● Polling with setInterval or similar methods.
● Using hooks like useEffect to synchronize with APIs when components mount or
update.

60. How do you ensure accessibility in a React application?

Answer: To ensure accessibility in a React application:

● Use semantic HTML elements.


● Add aria-* attributes for better screen reader support.
● Manage focus properly, especially for modal dialogs and interactive elements.
● Use libraries like react-axe to detect accessibility issues during development.

61. What is the difference between componentDidMount and useEffect?

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.

62. How can you create a modal component in React?

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: Data can be fetched in React using:

● Fetch API: Using fetch in useEffect for simple requests.


● Axios: A popular library for making HTTP requests with additional features like
interceptors.
● GraphQL: Using Apollo Client or Relay for managing data with GraphQL APIs.
● React Query: For managing server state and simplifying data fetching and caching.

64. How do you implement a debounce function in React?

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.

66. How can you use service workers in a React application?

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.

67. What is the purpose of shouldComponentUpdate?

Answer: shouldComponentUpdate is a lifecycle method in class components that allows you


to control whether a component should re-render based on changes in state or props. It can
help optimize performance by preventing unnecessary re-renders.

68. How do you handle nested routes in React Router?

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?

Answer: Pagination can be implemented by:

● Maintaining current page state using useState.


● Fetching data based on the current page, often using query parameters.
● Rendering only the relevant items for the current page and providing navigation controls
to change the page.

70. What are the benefits of using CSS Modules in a React application?

Answer: CSS Modules provide:

● Scoped styles, preventing class name collisions.


● Better maintainability with modularized styles.
● The ability to write CSS in a more organized way, improving readability and reducing
global styles.

71. How do you create a responsive layout in React?

Answer: A responsive layout can be achieved by:

● Using CSS Flexbox or Grid for layout structure.


● Media queries to adjust styles based on screen size.
● Libraries like Bootstrap or Material-UI that offer responsive design components.
● Utilizing custom Hooks to manage viewport size.

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.

73. How do you handle authentication tokens in a React app?

Answer: Authentication tokens can be handled by:

● Storing them in local storage or session storage.


● Using context or state management libraries to manage the authentication state across
the application.
● Attaching tokens to HTTP headers for authenticated API requests, often using Axios
interceptors for automatic handling.
74. What are controlled components, and how do they differ from
uncontrolled components?

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.

75. How do you handle environment variables in a React application?

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.

76. Explain the use of memo in functional components.

Answer: [Link] is a higher-order component that memoizes a functional component,


preventing it from re-rendering if its props haven't changed. It’s useful for optimizing
performance in components that receive the same props frequently.

77. What is the role of combineReducers in Redux?

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.

78. How can you integrate analytics tracking in a React application?

Answer: Analytics tracking can be integrated by:

● Using libraries like Google Analytics, Segment, or Mixpanel.


● Adding tracking code in useEffect to log page views and events.
● Utilizing a context or state management solution to centralize tracking logic.

79. How can you implement drag-and-drop functionality in a React app?

Answer: Drag-and-drop functionality can be implemented using libraries like


react-beautiful-dnd or react-dnd. These libraries provide hooks and components to
manage drag-and-drop interactions, state, and UI updates, simplifying the implementation.

80. What is the significance of using async/await in React for data


fetching?
Answer: Using async/await simplifies the syntax of asynchronous code, making it more
readable and easier to manage than promises. It helps to handle data fetching cleanly in
useEffect, allowing you to work with try/catch blocks for error handling without deeply
nested code

81. What is the purpose of [Link]?

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.

82. How do you manage multiple states in a single component?

Answer: Multiple states in a component can be managed using:

● Separate useState calls for each state value.


● The useReducer Hook for more complex state logic, allowing you to manage related
states in a single state object.

const initialState = { count: 0, text: '' };


const reducer = (state, action) => {
switch ([Link]) {
case 'increment':
return { ...state, count: [Link] + 1 };
case 'setText':
return { ...state, text: [Link] };
default:

return state;
}
};
const [state, dispatch] = useReducer(reducer, initialState);

83. What is the key prop in React, and why is it important?

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: Component libraries can be integrated by:

● Installing the library via npm or yarn.


● Importing components as needed into your application.
● Customizing styles, props, and behaviors according to the application's requirements.

Examples include Material-UI, Ant Design, or Bootstrap.

85. Explain the concept of "lifting state up" in React.

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.

86. What is the purpose of [Link]?

Answer: [Link] is a tool for highlighting potential problems in an application


during development. It activates additional checks and warnings, such as detecting deprecated
APIs, ensuring components are pure, and identifying side effects in render methods. It does not
impact production builds.

87. How do you use contextType in class components?

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

class MyComponent extends [Link] {


static contextType = MyContext;

render() {
const value = [Link];
return <div>{value}</div>;
}
}
88. How do you create a responsive navigation menu in React?

Answer: A responsive navigation menu can be created using:

● CSS Flexbox or Grid for layout.


● Media queries for adjusting styles based on screen size.
● State management to toggle visibility in mobile views, often using useState to manage
open/close states.

Example:

javascript

const [isOpen, setIsOpen] = useState(false);

const toggleMenu = () => {


setIsOpen(!isOpen);
};

// In the render
<nav>
<button onClick={toggleMenu}>Menu</button>
{isOpen && <ul>{/* Menu items */}</ul>}
</nav>

89. How do you optimize performance in a large React application?

Answer: Performance can be optimized by:

● Using [Link] to prevent unnecessary re-renders.


● Implementing code splitting and lazy loading with [Link] and Suspense.
● Memoizing calculations with useMemo.
● Using pagination or infinite scrolling for large lists.
● Avoiding inline functions in render methods and using useCallback.

90. What is the purpose of useTransition in React?


Answer: useTransition is a Hook that helps manage state transitions in a way that can
make the UI feel more responsive. It allows you to mark updates as "transitions," enabling React
to keep the UI responsive by prioritizing urgent updates over less critical ones.

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

const initialState = { name: '', email: '' };

const formReducer = (state, action) => {


switch ([Link]) {
case 'SET_FIELD':
return { ...state, [[Link]]: [Link] };
default:
return state;
}
};

const [state, dispatch] = useReducer(formReducer, initialState);

// Handling input change


const handleChange = (e) => {
dispatch({ type: 'SET_FIELD', field: [Link], value: [Link]
});
};

92. What are the benefits of using TypeScript with React?

Answer: Benefits of using TypeScript with React include:

● Static type checking, reducing runtime errors.


● Improved developer experience with better autocompletion and type inference.
● Enhanced code readability and maintainability.
● Early detection of bugs, especially in large codebases.

93. How can you handle errors in asynchronous code in React?

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.

Example with async/await:

javascript

Copy code

const fetchData = async () => {


try {
const response = await fetch(url);
if (![Link]) throw new Error('Network response was not ok');
const data = await [Link]();
setData(data);
} catch (error) {
setError(error);
}
};

94. How can you implement accessibility (a11y) best practices in React?

Answer: Accessibility best practices can be implemented by:

● Using semantic HTML elements.


● Adding aria-* attributes for screen reader support.
● Ensuring all interactive elements are keyboard accessible.
● Using proper color contrast and font sizes.
● Testing with tools like axe or Lighthouse for compliance.

95. How do you handle dynamic imports 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

const LazyComponent = [Link](() => import('./LazyComponent'));

// 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:

const { register, handleSubmit, formState: { errors } } = useForm();


const onSubmit = data => {
[Link](data);
};
// In the render
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('name', { required: true })} />
{[Link] && <span>This field is required</span>}
<input type="submit" />
</form>

97. How can you implement internationalization (i18n) in a React app?

Answer: Internationalization can be implemented using libraries like react-i18next or


react-intl. These libraries provide tools for managing translations, pluralization, and date
formatting, allowing you to easily switch languages in your application.

98. What is the purpose of the useSelector and useDispatch hooks in


Redux?
Answer: useSelector is a Hook that allows you to extract data from the Redux store state.
useDispatch is a Hook that provides a reference to the dispatch function, enabling you to
dispatch actions to update the store.

99. How do you create a custom hook in React?

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;
}

100. What is the role of a Provider in a Context API?

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

You might also like