[go: up one dir, main page]

0% found this document useful (0 votes)
6 views21 pages

X 2

JSX is a syntax extension for JavaScript used in React to describe UI components. ReactJS is a library for building user interfaces, emphasizing a component-based architecture, virtual DOM for performance, and unidirectional data flow. Key concepts include state management, props, lifecycle methods, and hooks like useState and useEffect for handling component logic and side effects.

Uploaded by

bedorat563
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)
6 views21 pages

X 2

JSX is a syntax extension for JavaScript used in React to describe UI components. ReactJS is a library for building user interfaces, emphasizing a component-based architecture, virtual DOM for performance, and unidirectional data flow. Key concepts include state management, props, lifecycle methods, and hooks like useState and useEffect for handling component logic and side effects.

Uploaded by

bedorat563
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
You are on page 1/ 21

JSX is a syntax extension for JavaScript that looks similar to

XML or HTML. It is used in React to describe what the UI


React Basics
should look like.
javascript
1. What is ReactJS? Copy code
// Example: JSX syntax
ReactJS is a JavaScript library for building user interfaces, const element = <h1>Hello, world!</h1>;
primarily developed and maintained by Facebook. It allows
developers to create large web applications that can update

and render efficiently in response to data changes.
7. How do you create components in React?
javascript
Copy code
// Example of a simple React component Components in React can be created using functions or
classes.
function Welcome(props) {
javascript
return <h1>Hello, {props.name}</h1>; Copy code
} // Functional component
function Welcome(props) {
○ return <h1>Hello, {props.name}</h1>;
2. Explain the key features of React. }
○ Component-Based: Build encapsulated
components that manage their own state.
○ Declarative: Design simple views for // Class component
each state in your application, and React class Welcome extends React.Component {
will efficiently update and render just the render() {
right components when your data return <h1>Hello,
changes. {this.props.name}</h1>;
○ Virtual DOM: React creates a virtual
}
DOM to improve performance.
}
Unidirectional Data Flow: Data flows in one direction,
making it easier to debug. ○
javascript 8. What are props in React?
Copy code
// Example: Component-based and declarative Props are inputs to a React component. They are passed to
class App extends React.Component { the component similarly to function arguments.
javascript
render() {
Copy code
return <h1>Hello, world!</h1>;
// Example: Using props
}
function Greeting(props) {
}
return <h1>Hello, {props.name}</h1>;
}

3. What are the differences between React and
Angular? ○
○ Library vs Framework: React is a 9. Explain the concept of state in React.
library, while Angular is a full-fledged
framework. State is a built-in object that holds property values that belong
○ Data Binding: React uses one-way data to the component. When the state object changes, the
binding, Angular uses two-way data component re-renders.
binding. javascript
○ DOM: React uses a virtual DOM, Angular Copy code
manipulates the real DOM directly. // Example: Using state in a class component
○ Learning Curve: React has a simpler class Clock extends React.Component {
learning curve compared to Angular. constructor(props) {
4. Explain the virtual DOM in React.
super(props);
this.state = { date: new Date() };
The virtual DOM is a lightweight copy of the real DOM. React
}
keeps a virtual representation of the UI in memory, which it
synchronizes with the real DOM using a process called
reconciliation. render() {
javascript return <h1>It is
Copy code {this.state.date.toLocaleTimeString()}.</h1>;
// Example: Updating the virtual DOM }
const element = <h1>Hello, world</h1>; }
ReactDOM.render(element,
document.getElementById('root')); ○
10. What is the difference between state and
○ props?
5. How does React achieve better performance ○ Props: Passed to the component (similar
with the virtual DOM? to function parameters), immutable.
○ React achieves better performance by ○ State: Managed within the component
using the virtual DOM to batch updates (similar to variables declared inside a
and perform efficient diffing and function), mutable.
reconciliation, minimizing direct
manipulations to the real DOM. Components and Props
6. What is JSX? Why is it used in React?
How do you create functional components in React?
javascript
Copy code ○ Props: Handled by the parent
// Example: Functional component component and passed down to the child
function Welcome(props) { component.
return <h1>Hello, {props.name}</h1>;
} State: Managed within the component, changes are handled
with setState or useState hook.
javascript
11.
Copy code
// Example: Handling state changes
How do you create class components in React?
class Counter extends React.Component {
javascript
Copy code constructor(props) {
// Example: Class component super(props);
class Welcome extends React.Component { this.state = { count: 0 };
render() { }
return <h1>Hello,
{this.props.name}</h1>; increment = () => {
} this.setState({ count:
} this.state.count + 1 });
}
12.
13. What are pure components in React? render() {
return (
Pure components are components that only re-render when <div>
their props or state change. They perform a shallow <p>Count:
comparison of props and state to determine if re-rendering is {this.state.count}</p>
necessary. <button
javascript onClick={this.increment}>Increment</button>
Copy code
</div>
// Example: PureComponent
);
class MyComponent extends React.PureComponent
}
{
}
render() {
return <h1>Hello,

{this.props.name}</h1>;
17. Explain the lifecycle methods of React
} components.
} ○ Lifecycle methods allow you to hook into
certain points of a component’s life.
○ ■ Mounting: constructor(),
14. What are higher-order components (HOC) in componentDidMount()
React? ■ Updating:
shouldComponentUpdate()
HOCs are functions that take a component and return a new , componentDidUpdate()
component with added functionality. ■ Unmounting:
javascript componentWillUnmount()
Copy code
// Example: Higher-order component
javascript
function withGreeting(WrappedComponent) { Copy code
return class extends React.Component { // Example: Lifecycle methods
render() { class MyComponent extends React.Component {
return <WrappedComponent componentDidMount() {
greeting="Hello" {...this.props} />; console.log('Component mounted');
} }
};
} componentDidUpdate() {
console.log('Component updated');
○ }

How do you pass props to components in React? componentWillUnmount() {


javascript console.log('Component will
Copy code
unmount');
// Example: Passing props
}
function App() {
return <Welcome name="Sara" />;
render() {
}
return <div>Hello</div>;
}
function Welcome(props) {
}
return <h1>Hello, {props.name}</h1>;
}

18. What is the significance of
15. shouldComponentUpdate method?
16. How do you handle props and state changes in
React components?
shouldComponentUpdate allows you to optimize Copy code
performance by preventing unnecessary re-renders. It returns // Example: Uncontrolled component
true by default, but you can override it to return false if the class UncontrolledInput extends
component does not need to update. React.Component {
javascript constructor(props) {
Copy code super(props);
// Example: shouldComponentUpdate
this.inputRef = React.createRef();
class MyComponent extends React.Component {
}
shouldComponentUpdate(nextProps,
nextState) {
handleSubmit = (event) => {
return nextProps.someValue !==
event.preventDefault();
this.props.someValue;
alert('Input value: ' +
}
this.inputRef.current.value);
}
render() {
return
render() {
<div>{this.props.someValue}</div>;
return (
}
<form
}
onSubmit={this.handleSubmit}>
<input type="text"
○ ref={this.inputRef} />
<button
How do you implement default props in a React type="submit">Submit</button>
component?
</form>
javascript
Copy code );
// Example: Default props }
class Greeting extends React.Component { }
static defaultProps = {
name: 'Guest' ○
};
State Management
render() {
return <h1>Hello, 21. What are the different ways to manage state in
{this.props.name}</h1>; React?
} ○ Local state: Managed within a
} component using useState or
setState.
○ Global state: Managed across multiple
19.
components using Context API or
20. What are controlled and uncontrolled
libraries like Redux.
components in React?
○ Derived state: State derived from props
or other state values.
Controlled Components: Form inputs whose values are ○ URL state: Managed through React
controlled by React state. Router for route parameters and query
javascript strings.
Copy code 22. Explain the useState hook in React.
// Example: Controlled component
class ControlledInput extends React.Component
useState is a hook that allows you to add state to functional
{ components.
constructor(props) { javascript
super(props); Copy code
this.state = { value: '' }; // Example: useState hook
} function Counter() {
const [count, setCount] = useState(0);
handleChange = (event) => {
this.setState({ value: return (
event.target.value }); <div>
} <p>You clicked {count} times</p>
<button onClick={() =>
render() { setCount(count + 1)}>Click me</button>
return <input </div>
value={this.state.value} );
onChange={this.handleChange} />; }
}
} ○
23. What is the useEffect hook used for in React?

useEffect is a hook for performing side effects in functional
Uncontrolled Components: Form inputs that maintain their components. It runs after the component renders.
own state. javascript
javascript Copy code
// Example: useEffect hook
function Timer() { ○
const [count, setCount] = useState(0); 26. Explain the Redux architecture and its core
principles.
○ Single Source of Truth: The state is
useEffect(() => {
stored in a single, centralized store.
const timer = setInterval(() => { ○ State is Read-Only: The state can only
setCount(prevCount => prevCount + be changed by emitting actions.
1);
}, 1000); Changes are Made with Pure Functions: Reducers specify
how the state changes in response to actions.
return () => clearInterval(timer); javascript
}, []); Copy code
// Example: Redux store, actions, and
return <div>Timer: {count}</div>; reducers
} const initialState = { count: 0 };

○ function reducer(state = initialState,


24. How do you manage global state in React action) {
applications? switch (action.type) {
case 'INCREMENT':
Use Context API or state management libraries like Redux or return { count: state.count + 1
MobX. };
javascript default:
Copy code return state;
// Example: Using Context API for global }
state }
const AppContext = React.createContext();
const store = createStore(reducer);
function AppProvider({ children }) {
const [state, setState] = useState({ store.dispatch({ type: 'INCREMENT' });
user: null });

return ( 27. How do you connect Redux with a React
<AppContext.Provider value={[state, application?
setState]}>
{children} Use the Provider component from react-redux to wrap
</AppContext.Provider> your app and the connect function or useSelector and
); useDispatch hooks to connect components to the Redux
} store.
javascript
function Component() { Copy code
const [state, setState] = // Example: Connecting Redux with React
useContext(AppContext); import { Provider, connect } from
return <div>User: {state.user}</div>; 'react-redux';
}
function mapStateToProps(state) {
○ return { count: state.count };
25. What are the differences between Redux and }
Context API for state management?
○ Redux: Centralized store, more function mapDispatchToProps(dispatch) {
boilerplate, powerful debugging tools. return {
increment: () => dispatch({ type:
Context API: Simpler, less boilerplate, no middleware, better 'INCREMENT' })
for smaller applications.
};
javascript
Copy code }
// Redux example
import { createStore } from 'redux'; function Counter({ count, increment }) {
return (
const initialState = { count: 0 }; <div>
<p>Count: {count}</p>
function reducer(state = initialState, <button
action) { onClick={increment}>Increment</button>
switch (action.type) { </div>
case 'INCREMENT': );
return { count: state.count + 1 }
};
default: const ConnectedCounter =
return state; connect(mapStateToProps,
} mapDispatchToProps)(Counter);
}
function App() {
const store = createStore(reducer); return (
<Provider store={store}> useEffect(() => {
<ConnectedCounter /> document.title = `You clicked
</Provider> ${count} times`;
); }, [count]);
}
return (
○ <div>
28. What is an action creator in Redux? <p>You clicked {count} times</p>
<button onClick={() =>
An action creator is a function that returns an action object. setCount(count + 1)}>Click me</button>
javascript </div>
Copy code );
// Example: Action creator }
function increment() {
return { type: 'INCREMENT' };

} 32. Explain the useState hook in detail.


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 }

31. What are hooks in React? Why were they ○


introduced? 34. How do you create custom hooks in React?

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

return ( 37. How do you implement routing in a React


<div> application?
<p>Count: {count}</p>
<button Use react-router-dom for declarative routing.
onClick={increment}>Increment</button> javascript
<button Copy code
onClick={decrement}>Decrement</button> // Example: Basic routing with
</div> react-router-dom
); import { BrowserRouter as Router, Route,
} Switch, Link } from 'react-router-dom';

○ 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";

componentDidCatch(error, info) { // Cleanup function (optional)


// Handle errors in the component return () => {
this.setState({ hasError: true }); document.title = "Original
} Title";
};
render() { }, []); // Empty dependency array ensures
if (this.state.hasError) { it runs only once
return <div>Error occurred</div>;
} return <div>My Component</div>;
return <div>My Component</div>; }
}
}

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

function Toolbar() { test('renders MyComponent with correct text',


return ( () => {
<div> render(<MyComponent />);
<ThemedButton /> const linkElement =
</div> screen.getByText(/some text/i);
); expect(linkElement).toBeInTheDocument();
} });
61. css
62. How do you perform unit testing on React Copy code
components? /* Example: styles.module.css */
○ Write unit tests to test individual .header {
components or functions in isolation. color: blue;
○ Use Jest for running tests and
}
assertions, and React Testing Library for
rendering components and querying the javascript
DOM. Copy code
// Example: Using CSS Modules in a component
import styles from './styles.module.css';
javascript
Copy code
// Example: Unit testing a React component function MyComponent() {
import { render, screen } from return <div
'@testing-library/react'; className={styles.header}>Styled with CSS
import MyComponent from './MyComponent'; Modules</div>;
}
test('renders MyComponent with correct text',
() => { 64.
render(<MyComponent />); 65. How do you use styled-components in React?
○ styled-components is a library that allows
const linkElement =
you to write CSS-in-JS.
screen.getByText(/some text/i); ○ It allows you to define styled components
expect(linkElement).toBeInTheDocument(); with tagged template literals.
});
javascript
// Example: Unit testing a function Copy code
function add(a, b) { // Example: Using styled-components
return a + b; import styled from 'styled-components';
}
const StyledButton = styled.button`
test('adds 1 + 2 to equal 3', () => { background-color: blue;
expect(add(1, 2)).toBe(3); color: white;
}); padding: 10px 20px;
border: none;
63. border-radius: 5px;

Styling in React &:hover {


background-color: darkblue;
61. What are the different ways to style }
components in React? `;
○ CSS: Standard CSS files.
○ Inline styles: Using the style attribute. function MyComponent() {
○ CSS-in-JS: Libraries like return <StyledButton>Styled
styled-components or emotion. Button</StyledButton>;
○ CSS Modules: Scoped CSS classes.
}

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.

const StyledDiv = styled.div` javascript


color: red; Copy code
`; // Example: Error Boundary component
class ErrorBoundary extends React.Component {
function MyComponent() { constructor(props) {
return <StyledDiv>Styled with super(props);
styled-components</StyledDiv>; this.state = { hasError: false };
} }

62. static getDerivedStateFromError(error) {


63. Explain CSS Modules in React. return { hasError: true };
○ CSS Modules are a way to scope CSS }
locally to avoid conflicts between different
components.
componentDidCatch(error, errorInfo) {
○ In CSS Modules, class names are
automatically scoped locally by default.
console.error("Error caught by Error javascript
Boundary:", error, errorInfo); Copy code
} // Example: Integrating D3.js with React
import React, { useRef, useEffect } from
render() { 'react';
if (this.state.hasError) { import * as d3 from 'd3';
return <h1>Something went
wrong.</h1>; function MyChart() {
} const ref = useRef();
return this.props.children;
} useEffect(() => {
} const svg = d3.select(ref.current)
.append('svg')
function MyComponent() { .attr('width', 500)
return ( .attr('height', 500);
<ErrorBoundary>
<ComponentThatMayError /> svg.append('circle')
</ErrorBoundary> .attr('cx', 250)
); .attr('cy', 250)
} .attr('r', 50)
.attr('fill', 'blue');
65. }, []);
66. What are Error Boundaries in React?
○ Error Boundaries are React components return <div ref={ref}></div>;
that catch JavaScript errors anywhere in }
their child component tree, log those
errors, and display a fallback UI instead
67.
of the component tree that crashed.
68. How do you use React with TypeScript?
○ They catch errors during rendering, in
○ Use TypeScript with React by installing
lifecycle methods, and in constructors of
the necessary TypeScript packages and
the whole tree below them.
setting up a tsconfig.json file.
○ Define types for props and state in your
javascript components.
Copy code
// Example: Implementing an Error Boundary
typescript
class ErrorBoundary extends React.Component { Copy code
constructor(props) { // Example: Using TypeScript with React
super(props); import React from 'react';
this.state = { hasError: false };
} interface MyComponentProps {
message: string;
static getDerivedStateFromError(error) { }
return { hasError: true };
} const MyComponent: React.FC<MyComponentProps>
= ({ message }) => {
componentDidCatch(error, errorInfo) { return <div>{message}</div>;
console.error("Error caught by Error };
Boundary:", error, errorInfo);
} export default MyComponent;

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

function reducer(state, action) { // Initial state


switch (action.type) { const initialState = { count: 0 };
case 'increment':
return { count: state.count + 1 // Reducer function
}; function counterReducer(state = initialState,
case 'decrement': action) {
return { count: state.count - 1 switch (action.type) {
}; case 'increment':
default: return { count: state.count + 1
throw new Error(); };
} case 'decrement':
} return { count: state.count - 1
};
const CountContext = React.createContext(); default:
return state;
function CountProvider({ children }) { }
const [state, dispatch] = }
useReducer(reducer, initialState);
return ( // Create Redux store
const store = createStore(counterReducer);
○ Use it when you have state logic that
// Action creators involves multiple sub-values or when the
const increment = () => ({ type: 'increment' next state depends on the previous one.
});
const decrement = () => ({ type: 'decrement' javascript
Copy code
});
// Example: Using useReducer hook
const initialState = { count: 0 };
// Dispatch actions
store.dispatch(increment());
function reducer(state, action) {
switch (action.type) {
72. store.dispatch(decrement()); case 'increment':
73. Explain Redux and its core principles.
return { count: state.count + 1
○ Redux is a state management library for
JavaScript applications. };
○ Core principles: case '
■ Single source of truth: The
state of your whole application 76.
is stored in an object tree
within a single store.
4o
■ State is read-only: The only
way to change the state is to
emit an action, an object continue from 71
describing what happened.
■ Changes are made with pure ChatGPT
functions: To specify how the javascript
state tree is transformed by Copy code
actions, you write pure // Example: Handling forms in React
reducers. function MyForm() {
const [name, setName] = useState('');
javascript
Copy code
const handleChange = (event) => {
// Example: Basic Redux setup
setName(event.target.value);
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 handleClick() { function MyComponent({ htmlContent }) {


history.push("/new-route"); const sanitizedContent =
} DOMPurify.sanitize(htmlContent);
return <div dangerouslySetInnerHTML={{
return ( __html: sanitizedContent }} />;
<button type="button" }
onClick={handleClick}>
Go to new route 73.
</button>
);
Deployment
}
```
73. How do you deploy a React application?
○ Build the Application: Use npm run
81. **What is the purpose of the Switch
build to create a production-ready build
component in React Router?**
of your application.
- The `Switch` component is used to group ○ Deploy to a Web Server: Upload the
`Route` components and ensures that only one build files to a web server or cloud
route is rendered at a time. service provider (e.g., AWS, Heroku,
- It renders the first child `Route` or Netlify, Vercel).
`Redirect` that matches the location. ○ Configure the Server: Ensure the
server serves the index.html file for all
routes to handle client-side routing.
```javascript
○ Continuous Integration/Continuous
Deployment (CI/CD): Use CI/CD tools to
automate the deployment process.
4o 74. What are the considerations for deploying a
React application?
continue from questions 71 ○ Environment Configuration: Use
environment variables for configuration
settings (e.g., API endpoints, feature return { count: state.count + 1
flags). };
○ Static Asset Handling: Ensure proper case 'decrement':
handling of static assets like images,
return { count: state.count - 1
fonts, and styles.
○ Caching and Performance: Implement };
caching strategies and performance default:
optimizations (e.g., code splitting, lazy throw new Error();
loading). }
○ Security: Ensure security best practices }
are followed (e.g., HTTPS, CSP, secure
headers).
const CountContext = React.createContext();
○ SEO and Metadata: Ensure proper SEO
and metadata configuration (e.g., meta
tags, Open Graph tags). function CountProvider({ children }) {
const [state, dispatch] =
Advanced Concepts useReducer(reducer, initialState);
return (
75. What are portals in React? <CountContext.Provider value={{
○ Portals provide a way to render children state, dispatch }}>
into a DOM node that exists outside the {children}
DOM hierarchy of the parent component. </CountContext.Provider>
○ Useful for rendering modals, tooltips, or );
any content that needs to visually break }
out of its container.
function Counter() {
javascript
const { state, dispatch } =
Copy code
useContext(CountContext);
// Example: Creating a portal
return (
import ReactDOM from 'react-dom';
<div>
<p>Count: {state.count}</p>
function Modal({ children }) {
<button onClick={() => dispatch({
return ReactDOM.createPortal(
type: 'increment' })}>Increment</button>
<div className="modal">
<button onClick={() => dispatch({
{children}
type: 'decrement' })}>Decrement</button>
</div>,
</div>
document.getElementById('modal-root')
);
);
}
}

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

const server = express();


const fetchUser = userId => {
return async dispatch => {
server.get('*', (req, res) => {
const response = await
const appString =
fetch(`/api/user/${userId}`);
ReactDOMServer.renderToString(<App />);
const user = await response.json();
res.send(`
dispatch({ type: 'USER_LOADED',
<html>
payload: user });
<head><title>SSR React
};
App</title></head>
};
<body>
<div
const store = createStore(rootReducer,
id="root">${appString}</div>
applyMiddleware(thunk));
<script
src="/bundle.js"></script>
91.
92. How do you handle asynchronous actions in </body>
Redux with Redux Thunk? </html>
○ Create an action creator that returns a `);
function. });
○ Inside the function, perform the
asynchronous operation and dispatch server.listen(3000, () => {
actions based on the result.
console.log('Server is running on port
3000');
javascript
});
Copy code
// Example: Handling async actions with Redux
Thunk 94.
const fetchData = () => {
return async dispatch => { Context and useContext Hook
dispatch({ type: 'FETCH_DATA_REQUEST'
}); 94. What is the useContext hook in React?
try {
○ The useContext hook allows you to return <div>Result:
consume a context value in a functional {memoizedValue}</div>;
component. }
○ It simplifies accessing the context
compared to using the
97.
Context.Consumer component.
98. What is the useCallback hook in React and
when do you use it?
javascript ○ useCallback is a hook that returns a
Copy code memoized version of the callback
// Example: Using useContext hook function.
const ThemeContext = ○ It is used to prevent unnecessary
React.createContext('light'); re-creations of the function, which can
improve performance, especially when
function ThemedComponent() { passing callbacks to child components.
const theme = useContext(ThemeContext);
return <div style={{ background: theme javascript
Copy code
=== 'dark' ? '#333' : '#FFF' }}>Themed
// Example: Using useCallback
Component</div>;
const MyComponent = ({ onClick }) => {
}
const handleClick = useCallback(() => {
onClick();
95.
}, [onClick]);
96. How do you use context to pass data through
the component tree in React?
○ Create a context using return <button onClick={
React.createContext.
○ Provide the context value using 99.
Context.Provider.
○ Consume the context value using 4o
useContext or Context.Consumer.
continue
javascript
Copy code ChatGPT
// Example: Passing data through context javascript
const UserContext = React.createContext(); Copy code
return <button
function App() { onClick={handleClick}>Click me</button>;
const user = { name: 'John', age: 30 }; };
return (
<UserContext.Provider value={user}> // Example usage
<UserProfile /> function App() {
</UserContext.Provider> const handleClick = () => {
); console.log('Button clicked!');
} };

function UserProfile() { return (


const user = useContext(UserContext); <div>
return <div>User: {user.name}</div>; <MyComponent
} onClick={handleClick} />
</div>
97. );
}
useMemo and useCallback Hooks ```

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
```

99. **How does React Concurrent Mode affect


the rendering pipeline?**
- Concurrent Mode enables React to
schedule and prioritize updates, allowing
more important updates (e.g., user
interactions) to interrupt less important
ones (e.g., rendering offscreen components).
- It helps in rendering more efficiently
and maintaining responsiveness even when
there are multiple updates happening
simultaneously.

```javascript
// Example: Concurrent mode placeholder
function App() {
return <h1>My App</h1>;
}
```

### React Suspense

100. **What is React Suspense and how does it


improve the user experience?**
- React Suspense is another experimental
feature that allows components to "suspend"
rendering while waiting for some asynchronous
operation to complete (e.g., data fetching).
- It improves the user experience by
providing a better way to handle loading
states and seamlessly integrate data fetching
with component rendering.

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

These examples and explanations cover a wide


range of topics in React, from basic concepts
to more advanced features and best practices.
Each example demonstrates how to implement
various functionalities in a React
application, helping you understand how to
apply these concepts in your own projects. If
you have any specific questions or need
further clarification on any topic, feel free
to ask!

You might also like