X 2
X 2
○
useState is a hook that allows you to add state to functional
29. Explain reducers in Redux.
components. It returns an array with two values: the current
state and a function to update it.
Reducers are pure functions that take the current state and javascript
an action as arguments and return a new state. Copy code
javascript // Example: useState hook
Copy code
function Counter() {
// Example: Reducer
const [count, setCount] = useState(0);
const initialState = { count: 0 };
return (
function reducer(state = initialState,
<div>
action) {
<p>You clicked {count} times</p>
switch (action.type) {
<button onClick={() =>
case 'INCREMENT':
setCount(count + 1)}>Click me</button>
return { count: state.count + 1
</div>
};
);
default:
}
return state;
}
○
}
33. Explain the useEffect hook in detail.
○
30. How does Redux store work? useEffect is a hook that performs side effects in functional
components. It runs after the render and can optionally clean
up after itself.
The Redux store holds the state of the application, allows javascript
access to state via getState(), dispatches actions via Copy code
dispatch(action), and registers listeners via // Example: useEffect hook
subscribe(listener). function Timer() {
javascript const [count, setCount] = useState(0);
Copy code
// Example: Redux store
useEffect(() => {
const store = createStore(reducer);
const timer = setInterval(() => {
setCount(prevCount => prevCount +
store.subscribe(() =>
1);
console.log(store.getState()));
}, 1000);
store.dispatch({ type: 'INCREMENT' });
return () => clearInterval(timer);
}, []);
○
return <div>Timer: {count}</div>;
Hooks }
Hooks are functions that let you use state and other React Custom hooks are functions that use other hooks to
features in functional components. They were introduced to encapsulate and reuse stateful logic.
provide a way to use state and lifecycle methods without javascript
writing class components. Copy code
javascript // Example: Custom hook
Copy code
function useCounter(initialCount = 0) {
// Example: useState and useEffect hooks
const [count, setCount] =
function Counter() {
useState(initialCount);
const [count, setCount] = useState(0);
const increment = () => setCount(count + <ExpensiveComponent
1); compute={compute} count={count} />
const decrement = () => setCount(count - <button onClick={() =>
1); setCount(count + 1)}>Increment</button>
</div>
return { count, increment, decrement }; );
} }
function Counter() { ○
const { count, increment, decrement } =
useCounter(); Routing and Navigation
○ function Home() {
35. What are the rules of hooks in React? return <h2>Home</h2>;
○ Only call hooks at the top level. }
Only call hooks from React function components or custom function About() {
hooks. return <h2>About</h2>;
javascript
}
Copy code
// Example: Valid use of hooks
function App() {
function Counter() {
return (
const [count, setCount] = useState(0);
<Router>
useEffect(() => {
<nav>
document.title = `You clicked
<Link to="/">Home</Link>
${count} times`;
<Link
}, [count]);
to="/about">About</Link>
return <button onClick={() =>
</nav>
setCount(count + 1)}>Click me</button>;
<Switch>
}
<Route exact path="/"
component={Home} />
○
36. How do you optimize performance with hooks? <Route path="/about"
○ Use useMemo to memoize expensive component={About} />
calculations. </Switch>
○ Use useCallback to memoize event </Router>
handlers. );
}
Use React.memo to prevent unnecessary re-renders of
functional components. ○
javascript 38. Explain the role of react-router in React
Copy code applications.
// Example: useMemo and useCallback hooks ○ react-router provides a declarative
function ExpensiveComponent({ compute, count way to handle routing in React
}) { applications, allowing for dynamic
const result = useMemo(() => routing, nested routes, and route
compute(count), [compute, count]); parameters.
39. How do you handle dynamic routing in React?
return <div>{result}</div>;
Use route parameters and useParams hook from
}
react-router-dom.
javascript
function ParentComponent() {
Copy code
const [count, setCount] = useState(0); // Example: Dynamic routing with
react-router-dom
const compute = useCallback((num) => { import { useParams } from 'react-router-dom';
// Expensive computation here
return num * 2; function UserProfile() {
}, []); const { userId } = useParams();
return <div>User ID: {userId}</div>;
return ( }
<div>
Forms and Data Handling (continued)
function App() {
return ( 41. How do you pass parameters in the URL using
<Router> React-router?
<Switch>
<Route path="/user/:userId" Use route parameters with the useParams hook.
component={UserProfile} /> javascript
</Switch> Copy code
</Router> // Example: Passing parameters in the URL
); import { BrowserRouter as Router, Route,
} Switch, useParams } from 'react-router-dom';
function UserProfile() {
○
40. What are nested routes in React-router? const { userId } = useParams();
return <div>User ID: {userId}</div>;
Nested routes allow you to render child routes within parent }
routes.
javascript function App() {
Copy code return (
// Example: Nested routes with <Router>
react-router-dom <Switch>
function Dashboard() { <Route path="/user/:userId"
return ( component={UserProfile} />
<div> </Switch>
<h2>Dashboard</h2> </Router>
<Switch> );
<Route }
path="/dashboard/overview"
component={Overview} /> ●
<Route
path="/dashboard/stats" component={Stats} />
Component Lifecycle
</Switch>
</div>
48. Explain the lifecycle of a React component.
); ○ Mounting: The component is being
} inserted into the DOM.
■ constructor()
function App() { ■ static
return ( getDerivedStateFromProp
<Router> s()
<Switch> ■ render()
<Route path="/dashboard" ■ componentDidMount()
component={Dashboard} /> ○ Updating: The component is being
</Switch> re-rendered as a result of changes to its
</Router> props or state.
); ■ static
} getDerivedStateFromProp
s()
○ ■ shouldComponentUpdate()
41. How do you pass parameters in the URL using ■ render()
React-router? ■ getSnapshotBeforeUpdate
()
Use route parameters with the useParams hook. ■ componentDidUpdate()
javascript ○ Unmounting: The component is being
Copy code removed from the DOM.
// Example: Passing parameters in the URL ■ componentWillUnmount()
function UserProfile() { ○ Error Handling: Called when there is an
error during rendering, in a lifecycle
const { userId } = useParams();
method, or in the constructor of any child
return <div>User ID: {userId}</div>; component.
} ■ static
getDerivedStateFromErro
function App() { r()
return ( ■ componentDidCatch()
<Router>
<Switch> javascript
<Route path="/user/:userId" Copy code
component={UserProfile} /> class MyComponent extends React.Component {
</Switch> constructor(props) {
</Router> super(props);
); this.state = { hasError: false };
}
○ }
static componentWillMount() {
getDerivedStateFromProps(nextProps, // Use componentDidMount instead
prevState) { }
// Return an object to update state,
or null to update nothing componentWillReceiveProps(nextProps) {
return null; // Use static
} getDerivedStateFromProps instead
}
componentDidMount() {
// Perform any initial data loading componentWillUpdate(nextProps, nextState)
} {
// Use getSnapshotBeforeUpdate
shouldComponentUpdate(nextProps, instead
nextState) { }
// Return false to prevent
re-rendering render() {
return true; return <div>My Component</div>;
} }
}
getSnapshotBeforeUpdate(prevProps,
prevState) { 52.
// Capture some information from the 53. How do you handle side effects in React
DOM before it is potentially changed components?
return null;
} Use the useEffect hook for handling side effects in
functional components. This includes tasks such as data
componentDidUpdate(prevProps, prevState, fetching, subscriptions, or manually changing the DOM.
javascript
snapshot) {
Copy code
// Perform any post-update tasks // Example: Handling side effects with
} useEffect
function MyComponent() {
componentWillUnmount() { useEffect(() => {
// Clean up any resources // Perform a side effect
} document.title = "New Title";
49.
50. What are the deprecated lifecycle methods in Performance Optimization
React 16?
○ The following lifecycle methods are 51. How do you optimize performance in React
deprecated and should not be used: applications?
■ componentWillMount() ○ Use React.memo: Memoize functional
■ componentWillReceivePro components to prevent unnecessary
ps() re-renders.
○ Use shouldComponentUpdate or
■ componentWillUpdate()
51. Instead, use: PureComponent: Optimize class
○ componentDidMount() for components by preventing unnecessary
updates.
componentWillMount()
○ Use the useMemo and useCallback
○ static hooks: Memoize values and functions.
getDerivedStateFromProps() for ○ Code splitting: Use dynamic imports to
componentWillReceiveProps() split code.
○ getSnapshotBeforeUpdate() for ○ Virtualize long lists: Use libraries like
componentWillUpdate() react-window or
react-virtualized.
javascript
Copy code javascript
// Deprecated lifecycle methods (avoid using Copy code
these) // Example: Using React.memo
class MyComponent extends React.Component {
const MyComponent = React.memo(function ○ Minimize re-renders: Use
MyComponent(props) { React.memo,
return <div>{props.value}</div>; shouldComponentUpdate, or
}); PureComponent.
○ Code splitting: Dynamically import
// Example: Using useMemo components.
○ Use virtualization for long lists: Use
function MyComponent({ items }) {
libraries like react-window or
const memoizedItems = useMemo(() =>
react-virtualized.
items.filter(item => item.active), [items]);
return <div>{memoizedItems.length}</div>;
javascript
}
Copy code
// Example: Avoiding inline functions
// Example: Using useCallback function MyComponent({ onClick }) {
function ParentComponent() { return <button onClick={onClick}>Click
const [count, setCount] = useState(0); Me</button>;
}
const handleIncrement = useCallback(() =>
{ function ParentComponent() {
setCount(count + 1); const [count, setCount] = useState(0);
}, [count]);
const handleClick = useCallback(() => {
return <ChildComponent setCount(count + 1);
onIncrement={handleIncrement} />; }, [count]);
}
return <MyComponent onClick={handleClick}
52. />;
53. Explain memoization in React.
}
○ Memoization is a performance
optimization technique to store the
results of expensive function calls and 56.
return the cached result when the same 57. How do you profile React applications for
inputs occur again. performance improvements?
○ In React, React.memo memoizes ○ Use the React DevTools Profiler to
functional components, useMemo measure the performance of React
components.
memoizes values, and useCallback
○ Use the built-in performance tools in
memoizes functions. browsers like Chrome's Performance
panel.
javascript
Copy code javascript
// Example: Using React.memo Copy code
const MyComponent = React.memo(function // Example: Using React DevTools Profiler
MyComponent(props) { // 1. Open React DevTools.
return <div>{props.value}</div>; // 2. Navigate to the Profiler tab.
}); // 3. Click on "Record" and perform actions
in your app.
// Example: Using useMemo // 4. Analyze the recorded profile for
function MyComponent({ items }) { performance bottlenecks.
const memoizedItems = useMemo(() =>
items.filter(item => item.active), [items]); 58.
return <div>{memoizedItems.length}</div>;
}
Context API
// Example: Using useCallback
55. What is Context API in React?
function ParentComponent() { ○ Context API provides a way to pass data
const [count, setCount] = useState(0); through the component tree without
having to pass props down manually at
const handleIncrement = useCallback(() => every level.
{ ○ It's used for sharing state, themes, or
setCount(count + 1); other common properties across
components.
}, [count]);
javascript
return <ChildComponent
Copy code
onIncrement={handleIncrement} />;
// Example: Creating and consuming context
}
const MyContext = React.createContext();
54.
function MyProvider({ children }) {
55. What are the performance best practices for
React applications? const value = "some value";
○ Avoid inline functions in render: Use return <MyContext.Provider
useCallback to memoize them. value={value}>{children}</MyContext.Provider>
○ Use production build: Ensure the app ;
is built for production. }
function ThemedButton() {
function MyComponent() { const theme = useContext(ThemeContext);
const context = useContext(MyContext); return <button style={{ background: theme
return <div>{context}</div>; === 'dark' ? '#333' : '#fff'
} }}>Button</button>;
}
56.
57. How do you create and consume context in 59.
React?
Testing
Creating context:
javascript
Copy code 58. How do you test React components?
const MyContext = ○ Use libraries like Jest for testing
JavaScript and React Testing Library for
React.createContext(defaultValue); testing React components.
○ Write unit tests for individual components
○ and integration tests for component
interactions.
Providing context:
javascript javascript
Copy code Copy code
function MyProvider({ children }) { // Example: Testing a React component with
const value = "some value"; React Testing Library
return <MyContext.Provider import { render, screen } from
value={value}>{children}</MyContext.Provider> '@testing-library/react';
; import MyComponent from './MyComponent';
}
test('renders MyComponent with correct text',
○ () => {
render(<MyComponent />);
Consuming context: const linkElement =
javascript screen.getByText(/some text/i);
Copy code expect(linkElement).toBeInTheDocument();
function MyComponent() { });
const context = useContext(MyContext);
return <div>{context}</div>; 59.
} 60. What are the popular testing libraries for React?
○ Jest: A JavaScript testing framework
○ used for unit tests, snapshot tests, and
58. When would you use Context API over props more.
drilling? ○ React Testing Library: A library for
○ Use Context API when you need to share testing React components by querying
state or data across multiple levels of the the DOM.
component tree, making the code ○ Enzyme: A JavaScript testing utility for
cleaner and avoiding the "props drilling" React, useful for shallow rendering and
problem. DOM manipulation.
○ Example: Sharing a theme or user
authentication status across many javascript
components. Copy code
// Example: Setting up Jest and React Testing
javascript Library
Copy code // Install Jest and React Testing Library
// Example: Using Context API to avoid props // npm install --save-dev jest
drilling @testing-library/react
const ThemeContext =
React.createContext('light'); // Add a test script in package.json
"scripts": {
function App() { "test": "jest"
return ( }
<ThemeContext.Provider value="dark">
<Toolbar /> // Write a test file (MyComponent.test.js)
</ThemeContext.Provider> import { render, screen } from
); '@testing-library/react';
} import MyComponent from './MyComponent';
javascript
66.
Copy code
// Example: Inline styles
function MyComponent() { Error Handling
return <div style={{ color: 'red'
}}>Styled with inline styles</div>; 64. How do you handle errors in React
} applications?
○ Use Error Boundaries to catch JavaScript
errors anywhere in their child component
// Example: CSS-in-JS with styled-components tree, log those errors, and display a
import styled from 'styled-components'; fallback UI.
render() { 69.
if (this.state.hasError) { 70. How do you integrate React with GraphQL?
return <h1>Something went ○ Use the Apollo Client to integrate React
wrong.</h1>; with GraphQL.
} ○ Set up an ApolloProvider and use the
return this.props.children; useQuery hook to fetch data.
}
} javascript
Copy code
// Example: Integrating React with GraphQL
67.
using Apollo Client
import React from 'react';
Integrations
import { ApolloProvider, ApolloClient,
InMemoryCache, useQuery, gql } from
66. How do you integrate React with other libraries '@apollo/client';
or frameworks?
○ Integrate React with other libraries or
frameworks by using standard const client = new ApolloClient({
import/export statements and embedding uri: 'https://example.com/graphql',
them within React components. cache: new InMemoryCache()
○ Example: Integrating a charting library });
like D3.js with React.
const GET_DATA = gql`
query GetData { <CountContext.Provider value={{
data { state, dispatch }}>
id {children}
value </CountContext.Provider>
} );
} }
`;
function Counter() {
function MyComponent() { const { state, dispatch } =
const { loading, error, data } = useContext(CountContext);
useQuery(GET_DATA); return (
<div>
if (loading) return <p>Loading...</p>; <p>Count: {state.count}</p>
if (error) return <p>Error :(</p>; <button onClick={() => dispatch({
type: 'increment' })}>Increment</button>
return ( <button onClick={() => dispatch({
<div> type: 'decrement' })}>Decrement</button>
{data.data.map(({ id, value }) => </div>
( );
<div key={id}>{value}</div> }
))}
</div> function App() {
); return (
} <CountProvider>
<Counter />
function App() { </CountProvider>
return ( );
<ApolloProvider client={client}> }
<MyComponent />
</ApolloProvider> 70.
); 71. Explain Redux and its core principles.
} ○ Redux is a state management library for
JavaScript applications.
○ Core principles:
71. ■ Single source of truth: The
state of your whole application
State Management is stored in an object tree
within a single store.
69. How do you manage global state in a React ■ State is read-only: The only
application? way to change the state is to
emit an action, an object
○ Use context and the useReducer hook
describing what happened.
for a built-in solution.
■ Changes are made with pure
○ Use state management libraries like
functions: To specify how the
Redux, MobX, or Zustand for more
state tree is transformed by
complex state management needs.
actions, you write pure
reducers.
javascript
Copy code
javascript
// Example: Managing global state with Copy code
context and useReducer // Example: Basic Redux setup
const initialState = { count: 0 }; import { createStore } from 'redux';
// Initial state
const handleSubmit = (event) => {
const initialState = { count: 0 };
event.preventDefault();
alert(`A name was submitted:
// Reducer function
${name}`);
function counterReducer(state = initialState,
};
action) {
switch (action.type) {
return (
case 'increment':
<form onSubmit={handleSubmit}>
return { count: state.count + 1
<label>
};
Name:
case 'decrement':
<input type="text"
return { count: state.count - 1
value={name} onChange={handleChange} />
};
</label>
default:
<button
return state;
type="submit">Submit</button>
}
</form>
}
);
}
// Create Redux store
```
const store = createStore(counterReducer);
### React Router
// Action creators
const increment = () => ({ type: 'increment'
79. **What is React Router?**
});
- React Router is a standard library for
const decrement = () => ({ type: 'decrement'
routing in React.
});
- It enables the navigation among views
of various components in a React application,
// Dispatch actions
allows changing the browser URL, and keeps
store.dispatch(increment());
the UI in sync with the URL.
store.dispatch(decrement());
```javascript
74.
// Example: Basic React Router setup
75. What is the useReducer hook and when would
you use it? import { BrowserRouter as Router, Route,
○ The useReducer hook is an alternative Switch } from 'react-router-dom';
to useState for managing complex
state logic. function App() {
return (
<Router>
<Switch> ChatGPT
<Route path="/about">
<About /> Security
</Route>
<Route path="/users"> 71. What are some security best practices in React
<Users /> applications?
</Route> ○ Sanitize Inputs: Always sanitize and
<Route path="/"> validate user inputs to prevent injection
attacks.
<Home />
○ Avoid Dangerous APIs: Avoid using
</Route>
dangerouslySetInnerHTML to
</Switch> prevent XSS attacks. Use libraries like
</Router> DOMPurify to sanitize HTML content if
); necessary.
} ○ Use HTTPS: Ensure your application
uses HTTPS to encrypt data between the
function Home() { client and server.
○ Content Security Policy (CSP):
return <h2>Home</h2>;
Implement a CSP to mitigate XSS and
} data injection attacks.
○ Security Headers: Use security headers
function About() { like X-Content-Type-Options,
return <h2>About</h2>; X-Frame-Options,
} Strict-Transport-Security, and
X-XSS-Protection.
function Users() { ○ Environment Variables: Store sensitive
return <h2>Users</h2>; data (e.g., API keys) in environment
} variables, not in the source code.
``` 72. How do you prevent XSS attacks in React?
○ Avoid dangerouslySetInnerHTML:
Do not use
80. **How do you perform programmatic
dangerouslySetInnerHTML unless
navigation in React Router?**
absolutely necessary and sanitize input.
- Use the `useHistory` hook from React ○ Escape User Inputs: Always escape
Router to programmatically navigate to a any user inputs before rendering them in
different route. the UI.
○ Use Trusted Libraries: Use libraries like
```javascript DOMPurify to sanitize HTML content.
// Example: Programmatic navigation using ○ Content Security Policy (CSP):
Implement CSP to reduce the risk of XSS
useHistory
attacks.
import { useHistory } from
'react-router-dom';
javascript
Copy code
function MyComponent() { // Example: Using DOMPurify to sanitize HTML
let history = useHistory(); import DOMPurify from 'dompurify';
function App() {
function App() {
return (
return (
<CountProvider>
<div>
<Counter />
<h1>My App</h1>
</CountProvider>
<Modal>
);
<p>This is a modal!</p>
}
</Modal>
</div>
); 78.
79. What are lazy loading and code splitting in
}
React?
○ Lazy Loading: Technique to defer
76. loading of non-critical resources at the
77. How do you handle state management without initial load time. Improves performance
Redux? by loading components only when they
○ Context API and useReducer: Use are needed.
React's Context API combined with the ○ Code Splitting: Breaking up the
useReducer hook to manage global codebase into smaller chunks that can
state. be loaded on demand. Usually
○ Hooks: Use custom hooks to implemented using React.lazy and
encapsulate and manage state logic. Suspense.
○ Third-party Libraries: Use other state
management libraries like MobX, Recoil, javascript
or Zustand. Copy code
// Example: Implementing lazy loading and
javascript code splitting
Copy code
import React, { Suspense, lazy } from
// Example: Managing state with Context API
'react';
and useReducer
const initialState = { count: 0 };
const LazyComponent = lazy(() =>
import('./LazyComponent'));
function reducer(state, action) {
switch (action.type) {
function App() {
case 'increment':
return (
<div>
<h1>My App</h1> />
<Suspense );
fallback={<div>Loading...</div>}> }
<LazyComponent />
</Suspense> 80.
</div> 81. How do you handle routing transitions in
); React?
} ○ React Transition Group: Use React
Transition Group to animate route
transitions.
80.
○ Custom Animations: Implement custom
81. How do you handle animations in React?
animations using CSS or animation
○ CSS Animations: Use CSS animations
libraries.
and transitions for simple animations.
○ React Transition Group: A library that
provides components for managing javascript
component transition effects. Copy code
○ Framer Motion: A popular animation // Example: Route transitions with React
library for React that provides declarative Transition Group
animations and gestures. import { Switch, Route, useLocation } from
'react-router-dom';
javascript import { CSSTransition, TransitionGroup }
Copy code from 'react-transition-group';
// Example: Using React Transition Group
import { CSSTransition, TransitionGroup }
function App() {
from 'react-transition-group';
const location = useLocation();
return (
function TodoList({ items }) {
<TransitionGroup>
return (
<CSSTransition key={location.key}
<TransitionGroup>
classNames="fade" timeout={300}>
{items.map((item) => (
<Switch location={location}>
<CSSTransition key={item.id}
<Route exact path="/"
timeout={500} classNames="fade">
component={Home} />
<div>{item.text}</div>
<Route path="/about"
</CSSTransition>
component={About} />
))}
<Route path="/contact"
</TransitionGroup>
component={Contact} />
);
</Switch>
}
</CSSTransition>
</TransitionGroup>
82. );
}
Real-world Scenarios
82.
79. How do you handle authentication in a React
application?
○ Authentication Libraries: Use libraries React Native
like Firebase, Auth0, or JWT for
authentication. 81. What is React Native?
○ Context API: Manage authentication ○ React Native is a framework for building
state using Context API and hooks. native mobile applications using React.
○ Protected Routes: Implement protected ○ It allows developers to use React to build
routes that require authentication. mobile apps with native components for
iOS and Android.
javascript 82. How does React Native differ from React?
Copy code ○ Rendering: React Native uses native
components, while React uses HTML
// Example: Protected Route
and the browser's DOM.
import { Route, Redirect } from ○ Styling: React Native uses StyleSheet
'react-router-dom'; and JavaScript objects for styling,
whereas React typically uses CSS.
function PrivateRoute({ component: Component, ○ Navigation: React Native uses libraries
...rest }) { like react-navigation, while React
const isAuthenticated = /* logic to uses react-router.
determine if authenticated */;
return ( javascript
<Route Copy code
{...rest} // Example: Basic React Native component
render={(props) => import React from 'react';
isAuthenticated ? ( import { View, Text, StyleSheet } from
<Component {...props} /> 'react-native';
) : (
<Redirect to="/login" /> function App() {
) return (
} <View style={styles.container}>
<Text>Hello, React Native!</Text> ○ ARIA Roles: Use ARIA roles and
</View> attributes to provide additional context to
); screen readers.
○ Focus Management: Ensure proper
}
focus management, especially for
interactive elements.
const styles = StyleSheet.create({ ○ Testing Tools: Use tools like aXe,
container: { Lighthouse, and screen readers to test
flex: 1, accessibility.
justifyContent: 'center',
alignItems: 'center', javascript
}, Copy code
}); // Example: Using ARIA attributes
function AccessibleButton() {
export default App; return (
<button aria-label="Close"
83. onClick={() => console.log('Closed')}>
84. How do you create a mobile application using <span aria-hidden="true">×</span>
React Native? </button>
○ Setup Environment: Install Node.js, );
React Native CLI, Android Studio, and }
Xcode (for iOS).
○ Create Project: Use react-native
87.
init to create a new React Native 88. What are ARIA roles in React?
project. ○ ARIA (Accessible Rich Internet
○ Develop and Test: Write React Native Applications) roles provide extra
code and test it on Android and iOS information to assistive technologies
emulators or real devices. about the purpose and behavior of
○ Build and Deploy: Build the app for elements.
release and deploy it to app stores. ○ They are used to enhance the
accessibility of web applications by
bash defining roles, states, and properties.
Copy code
npx react-native init MyApp javascript
cd MyApp Copy code
npx react-native run-android # or npx // Example: Using ARIA roles
react-native run-ios function Navigation() {
return (
85. <nav aria-label="Main navigation">
<ul>
Performance Monitoring and Optimization <li><a
href="#home">Home</a></li>
84. How do you monitor performance in a React <li><a
application? href="#about">About</a></li>
○ React Developer Tools: Use the React <li><a
DevTools to inspect the component tree href="#contact">Contact</a></li>
and measure performance. </ul>
○ Browser Performance Tools: Use </nav>
browser performance tools like Chrome
);
DevTools for detailed performance
analysis. }
○ Third-party Monitoring Services:
Integrate services like New Relic, Sentry, 89.
or Datadog to monitor performance in
production.
85. What tools would you use to identify Redux Middleware
performance bottlenecks in React?
○ React Profiler: Use the React Profiler 88. What is Redux middleware? Give examples.
API to measure performance. ○ Redux middleware provides a way to
○ Chrome DevTools: Utilize Chrome interact with dispatched actions before
DevTools for performance profiling and they reach the reducer.
analysis. ○ Examples: redux-thunk, redux-saga,
○ Web Vitals: Use the Web Vitals library to and redux-logger.
measure key performance metrics.
○ Lighthouse: Use Lighthouse to audit
javascript
performance, accessibility, and best
Copy code
practices.
// Example: Applying middleware in Redux
import { createStore, applyMiddleware } from
Accessibility 'redux';
import thunk from 'redux-thunk';
86. How do you ensure accessibility in React import rootReducer from './reducers';
applications?
○ Semantic HTML: Use semantic HTML
elements to improve accessibility. const store = createStore(rootReducer,
applyMiddleware(thunk));
89. const response = await
90. How do you write custom middleware for fetch('/api/data');
Redux? const data = await
○ Custom middleware is a function that
response.json();
receives store and returns a function
dispatch({ type:
that takes next, which in turn returns a
'FETCH_DATA_SUCCESS', payload: data });
function that takes action.
} catch (error) {
dispatch({ type:
javascript
'FETCH_DATA_FAILURE', error });
Copy code
// Example: Custom logging middleware }
const loggerMiddleware = store => next => };
action => { };
console.log('Dispatching:', action);
let result = next(action); 93.
console.log('Next state:',
store.getState()); Server-side Rendering (SSR)
return result;
}; 92. What is Server-side Rendering (SSR) in React?
○ SSR is the process of rendering React
const store = createStore(rootReducer, components on the server and sending
the HTML to the client.
applyMiddleware(loggerMiddleware));
○ It improves performance and SEO by
delivering fully rendered pages on the
91. first request.
93. How do you implement SSR in a React
application?
Redux Thunk
○ Use a framework like Next.js that
provides built-in support for SSR.
90. What is Redux Thunk used for? ○ Alternatively, set up your own SSR using
○ Redux Thunk is middleware that allows Node.js and libraries like Express and
you to write action creators that return a ReactDOMServer.
function instead of an action.
○ It is commonly used for handling
javascript
asynchronous logic like API calls.
Copy code
// Example: Basic SSR setup with Express
javascript
import express from 'express';
Copy code
import React from 'react';
// Example: Redux Thunk for async actions
import ReactDOMServer from
import { createStore, applyMiddleware } from
'react-dom/server';
'redux';
import App from './App';
import thunk from 'redux-thunk';
96. What is the useMemo hook in React and when ### React Concurrent Mode
do you use it?
○ useMemo is a hook that memoizes a 98. **What is React Concurrent Mode and what
computed value, recomputing it only problem does it solve?**
when its dependencies change. - React Concurrent Mode is an
○ It is used to optimize performance by experimental feature that aims to improve the
avoiding expensive calculations on every
responsiveness and user experience of React
render.
applications by allowing React to interrupt
rendering work to handle higher-priority
javascript
Copy code updates (like user interactions) without
// Example: Using useMemo blocking the browser's main thread.
const expensiveCalculation = (num) => { - It addresses the problem of janky and
// expensive computation unresponsive user interfaces by enabling
return num * 2; smoother interactions and animations.
};
```javascript
function MyComponent({ number }) { // Example: Concurrent mode placeholder
const memoizedValue = useMemo(() => function App() {
expensiveCalculation(number), [number]); return <h1>My App</h1>;
} 3.5
```
```javascript
// Example: Concurrent mode placeholder
function App() {
return <h1>My App</h1>;
}
```
```javascript
// Example: Using React Suspense for data
fetching
import { Suspense } from 'react';
function UserProfile() {
// Suspense wraps components that may
need to wait for async data
return (
<Suspense
fallback={<div>Loading...</div>}>
<UserData />
</Suspense>
);
}
function UserData() {
// Simulate fetching user data
const userData = fetchUserData();
return <div>User:
{userData.name}</div>;
}
```