└── README.md
/README.md:
--------------------------------------------------------------------------------
1 | # React-Interview-Preparation🔥🔥
2 |
3 |
4 |
5 |
6 | ## 1) What is React, and how is it different from other frameworks?
7 | - React is a JavaScript library for building user interfaces, developed by Facebook. It focuses only on the view layer and provides tools for creating reusable UI components. Unlike full-fledged frameworks like Angular, which include built-in tools for routing and state management, React relies on external libraries (e.g., React Router for routing, Redux for state management).
8 | Example:
9 | ```bash
10 | import React from 'react';
11 | function App() {
12 | return
Hello, React!
;
13 | }
14 | export default App;
15 | ```
16 | ## 2)Why use React.js for front-end development?
17 | - Component-based architecture: Helps build reusable and maintainable UI components.
18 | - Virtual DOM: Enhances performance by minimizing direct manipulation of the real DOM.
19 | - Rich Ecosystem: Libraries like Redux and React Router provide additional capabilities.
20 | #### Example:
21 | - A button component can be reused:
22 | ```bash
23 | function Button({ label }) {
24 | return ;
25 | }
26 | // Reused multiple times
27 |
28 |
29 | ```
30 | ## 3)Explain the concept of the Virtual DOM.
31 | - The Virtual DOM is a lightweight in-memory representation of the real DOM. When the UI updates, React calculates the difference (called diffing) between the current and new Virtual DOM and updates only the changed parts in the real DOM. This reduces the performance cost of DOM manipulation.
32 | #### Example:
33 | - If you update only one item in a list, React avoids re-rendering the entire list and updates just that item.
34 | ## 4) What is JSX, and why is it used in React?
35 | - JSX is a syntax extension of JavaScript that looks like HTML. It’s used in React because it makes code more readable and easier to write. JSX gets transpiled into React.createElement calls, which create React elements.
36 | #### Example:
37 | ```bash
38 | const element =
Hello, World!
; // JSX
39 | ```
40 | #### Transpiled to:
41 | ```bash
42 | const element = React.createElement('h1', null, 'Hello, World!');
43 | ```
44 | ## 5) What is a React component?
45 | - A React component is a reusable piece of UI logic and markup. It can be a functional component (simpler) or a class component (more complex).
46 | #### Example:
47 | ```bash
48 | // Functional Component
49 | function Welcome() {
50 | return
;
57 | }
58 | }
59 | ```
60 | ## 6) Differentiate between functional and class components.
61 | #### Functional components:
62 | - Simpler, written as functions.
63 | - Use React hooks like useState and useEffect to handle state and lifecycle methods.
64 | #### Class components:
65 | - Written as ES6 classes.
66 | - Use state and lifecycle methods like componentDidMount.
67 | #### Example:
68 | ```bash
69 | // Functional Component with Hooks
70 | function Counter() {
71 | const [count, setCount] = React.useState(0);
72 | return ;
73 | }
74 |
75 | // Class Component
76 | class Counter extends React.Component {
77 | state = { count: 0 };
78 | increment = () => this.setState({ count: this.state.count + 1 });
79 | render() {
80 | return ;
81 | }
82 | }
83 | ```
84 | ## 7) What is the role of render() in a class component?
85 | - The render() method defines what to display in the UI. It returns JSX.
86 | #### Example:
87 | ```bash
88 | class App extends React.Component {
89 | render() {
90 | return
Hello, World!
;
91 | }
92 | }
93 | ```
94 | ## 8) What is the difference between state and props?
95 | ### State:
96 |
97 | - Local to a component and mutable.
98 | - Defined using useState (functional components) or this.state (class components).
99 | ### Props:
100 |
101 | - Passed from parent to child components.
102 | - Immutable in the child component.
103 | #### Example:
104 | ```bash
105 | function Child({ message }) {
106 | return
{message}
; // Uses props
107 | }
108 |
109 | function Parent() {
110 | return ;
111 | }
112 | ```
113 | ## 9) How do you pass data between parent and child components?
114 | - Data is passed via props. For passing functions, you can also use callback props.
115 | #### Example:
116 | ```bash
117 | function Parent() {
118 | const showAlert = () => alert('Button clicked!');
119 | return ;
120 | }
121 |
122 | function Child({ onClick }) {
123 | return ;
124 | }
125 | ```
126 | ## 10) What are React keys, and why are they important?
127 | - Keys help React identify which items in a list have changed, preventing unnecessary re-renders.
128 | #### Example:
129 | ```bash
130 | const items = ['Apple', 'Banana', 'Cherry'];
131 | items.map((item, index) =>
{item}
);
132 | ```
133 | ## 11) How do you handle events in React?
134 | - Events are handled using camelCase attributes and event handler functions.
135 | #### Example:
136 | ```bash
137 | function App() {
138 | const handleClick = () => alert('Button Clicked!');
139 | return ;
140 | }
141 | ```
142 | ## 12) What is two-way binding in React?
143 | - Two-way binding means synchronizing data between the component’s state and the UI. React does not have built-in two-way binding; you implement it manually using onChange and value.
144 | #### Example:
145 | ```bash
146 | function App() {
147 | const [text, setText] = React.useState('');
148 | return setText(e.target.value)} />;
149 | }
150 | ```
151 | ## 13) What are React fragments, and why are they used?
152 | - Fragments let you group elements without adding extra nodes to the DOM.
153 | #### Example:
154 |
155 | ```bash
156 | <>
157 |
Title
158 |
Paragraph
159 | >
160 | ```
161 | ## 14) Explain controlled vs. uncontrolled components.
162 | - Controlled components: The value is controlled by React state.
163 | - Uncontrolled components: The value is controlled by the DOM.
164 | #### Example (Controlled):
165 |
166 | ```bash
167 | function App() {
168 | const [value, setValue] = React.useState('');
169 | return setValue(e.target.value)} />;
170 | }
171 | ```
172 | #### Example (Uncontrolled):
173 |
174 | ```bash
175 | function App() {
176 | const inputRef = React.useRef();
177 | return ;
178 | }]
179 | ```
180 |
181 | ## 15) How do you implement forms in React?
182 | - Forms are implemented using controlled components to track the input values.
183 | #### Example:
184 |
185 | ```bash
186 | function Form() {
187 | const [name, setName] = React.useState('');
188 | const handleSubmit = (e) => {
189 | e.preventDefault();
190 | alert(`Hello, ${name}!`);
191 | };
192 | return (
193 |
197 | );
198 | }
199 | ```
200 | ## 16) What is defaultProps, and how is it used?
201 | - defaultProps provides default values for props if none are supplied.
202 | #### Example:
203 |
204 | ```bash
205 | function Greeting({ name }) {
206 | return
Hello, {name}
;
207 | }
208 | Greeting.defaultProps = { name: 'Guest' };
209 | ````
210 | ## 17) What is propTypes, and why is it used?
211 | - propTypes validate the types of props a component receives. It’s useful for debugging.
212 | #### Example:
213 |
214 | ```bash
215 | Greeting.propTypes = { name: PropTypes.string.isRequired };
216 | ```
217 | ## 18) Explain the React component lifecycle.
218 | - Mounting: Component is created (componentDidMount).
219 | - Updating: Props or state change -(componentDidUpdate).
220 | - Unmounting: Component is removed (componentWillUnmount).
221 | #### Example:
222 |
223 | ```bash
224 | class App extends React.Component {
225 | componentDidMount() {
226 | console.log('Mounted');
227 | }
228 | componentWillUnmount() {
229 | console.log('Unmounted');
230 | }
231 | render() {
232 | return
Hello
;
233 | }
234 | }
235 | ```
236 | ## 19) What is setState, and how does it work?
237 | - setState updates the component’s state and triggers a re-render. It works asynchronously to batch updates.
238 | #### Example:
239 |
240 | ```bash
241 | this.setState({ count: this.state.count + 1 });
242 | ```
243 | ## 20) Why is it important to use an updater function in setState?
244 | - When multiple state updates happen, the previous state might not be immediately available. The updater function ensures updates are based on the latest state.
245 | #### Example:
246 |
247 | ```bash
248 | this.setState((prevState) => ({ count: prevState.count + 1 }));
249 | ```
250 | ## 21) What are React refs, and why are they used?
251 | - Refs provide a way to access DOM elements or React elements directly without re-rendering the component.
252 | - Use Cases: Managing focus, triggering animations, or integrating third-party libraries.
253 | #### Example:
254 |
255 | ```bash
256 | function App() {
257 | const inputRef = React.useRef(null);
258 |
259 | const focusInput = () => {
260 | inputRef.current.focus();
261 | };
262 |
263 | return (
264 | <>
265 |
266 |
267 | >
268 | );
269 | }
270 | ```
271 | ## 22) How does React handle DOM updates efficiently?
272 | - React uses the Virtual DOM to optimize updates. It compares the current Virtual DOM with the previous one using a process called diffing. Only the changed parts of the real DOM are updated.
273 |
274 | #### Example:
275 | - When updating a list, React will only update the changed list items instead of re-rendering the entire list.
276 |
277 | ## 23) What are Higher-Order Components (HOCs)?
278 | - An HOC is a function that takes a component and returns a new component, often used to share logic between components.
279 | #### Example:
280 |
281 | ```bash
282 | function withLogger(WrappedComponent) {
283 | return function EnhancedComponent(props) {
284 | console.log('Props:', props);
285 | return ;
286 | };
287 | }
288 |
289 | const ButtonWithLogger = withLogger(Button);
290 | ```
291 |
292 | ## 24) What are CSS modules in React?
293 | - CSS Modules allow you to scope CSS locally to a component to avoid naming conflicts.
294 | #### Example:
295 |
296 | ```bash
297 | /* styles.module.css */
298 | .title {
299 | color: green;
300 | }
301 | ```
302 | ```bash
303 | import styles from './styles.module.css';
304 | function App() {
305 | return
Scoped Style
;
306 | }
307 | ```
308 | ## 25) What is the difference between componentDidMount and componentWillUnmount?
309 | - componentDidMount: Runs after the component is mounted. Used for data fetching or subscriptions.
310 | - componentWillUnmount: Runs before the component is removed. Used for cleanup (e.g., removing event listeners).
311 | #### Example:
312 | ```bash
313 | class App extends React.Component {
314 | componentDidMount() {
315 | console.log('Mounted');
316 | }
317 | componentWillUnmount() {
318 | console.log('Unmounting');
319 | }
320 | render() {
321 | return
;
345 | }
346 | ```
347 | ## 28) How do you share data between sibling components?
348 | - Data can be shared using a common parent component and passing props. Alternatively, you can use state management like Redux or Context API.
349 | #### Example:
350 |
351 | ```bash
352 | function Parent() {
353 | const [data, setData] = React.useState('Hello');
354 | return (
355 | <>
356 |
357 |
358 | >
359 | );
360 | }
361 | ```
362 | ## 29) What is a React Portal?
363 | - React Portals allow rendering components outside the DOM hierarchy of the parent.
364 | #### Example:
365 |
366 | ```bash
367 | ReactDOM.createPortal(
368 |
;
394 | });
395 | ```
396 | ## 32) How do you prevent unnecessary re-renders in React?
397 | - Use React.memo for functional components.
398 | - Use shouldComponentUpdate or PureComponent in class components.
399 | - Avoid inline functions/objects as props.
400 | - Use useMemo or useCallback for optimization.
401 | #### Example (useCallback):
402 | ```bash
403 | const handleClick = React.useCallback(() => { console.log('Clicked'); }, []);
404 | ```
405 | ## 33) How do you implement code splitting in React?
406 | - Code splitting breaks large bundles into smaller chunks using React.lazy and dynamic imports.
407 | #### Example:
408 |
409 | ```bash
410 | const Component = React.lazy(() => import('./Component'));
411 | ```
412 | ## 34) What is the difference between a library and a framework? Is React a library or framework?
413 | - Library: A collection of tools to help build applications (React).
414 | - Framework: Provides a complete structure for application development (Angular).
415 | - React is a library focused on UI.
416 | ## 35) How do you fetch data in React applications?
417 | - Data can be fetched using fetch, Axios, or third-party libraries. Typically, data fetching is done in useEffect or lifecycle methods.
418 | #### Example:
419 |
420 | ```bash
421 | function App() {
422 | const [data, setData] = React.useState([]);
423 | React.useEffect(() => {
424 | fetch('https://jsonplaceholder.typicode.com/posts')
425 | .then((res) => res.json())
426 | .then((data) => setData(data));
427 | }, []);
428 | return
{data.map((item) =>
{item.title}
)}
;
429 | }
430 | ```
431 | ## 36)Explain the purpose of the useEffect hook.
432 | - useEffect manages side effects in functional components, like fetching data, updating the DOM, or subscribing to events. It runs after the component renders or when dependencies change.
433 |
434 | #### Example:
435 |
436 | ```bash
437 | import { useEffect, useState } from 'react';
438 |
439 | function App() {
440 | const [data, setData] = useState([]);
441 |
442 | useEffect(() => {
443 | fetch('https://jsonplaceholder.typicode.com/posts')
444 | .then((response) => response.json())
445 | .then((data) => setData(data));
446 | }, []); // Empty array ensures it runs once after initial render
447 |
448 | return
{data.map((item) =>
{item.title}
)}
;
449 | }
450 | ```
451 | ## 37)How do you use React Router?
452 | - React Router allows navigation between different pages in a React app. It provides components like Routes, Route, and Link for routing.
453 |
454 | #### Example:
455 |
456 | ```bash
457 | import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
458 |
459 | function App() {
460 | return (
461 |
462 |
466 |
467 | } />
468 | } />
469 |
470 |
471 | );
472 | }
473 |
474 | function Home() {
475 | return
;
480 | }
481 | ```
482 | ## 38) How do you manage routing for nested components?
483 | - Use nested elements within parent routes to define nested routing.
484 |
485 | #### Example:
486 |
487 | ```bash
488 |
489 | }>
490 | } />
491 | } />
492 |
493 | ;
494 | ```
495 | - Navigating to /dashboard/profile will render Dashboard and Profile.
496 |
497 | ## 39) What is the purpose of useParams in React Router?
498 | - useParams retrieves route parameters from the URL.
499 |
500 | #### Example:
501 |
502 | ```bash
503 | import { useParams } from 'react-router-dom';
504 |
505 | function Post() {
506 | const { id } = useParams();
507 | return
Post ID: {id}
;
508 | }
509 |
510 | // Route definition:
511 | } />;
512 | ```
513 | - Navigating to /post/123 will display Post ID: 123.
514 |
515 | ## 40) How do you handle redirection in React?
516 | - Use the Navigate component to redirect users programmatically.
517 |
518 | #### Example:
519 |
520 | ```bash
521 | import { Navigate } from 'react-router-dom';
522 |
523 | function Protected({ isLoggedIn }) {
524 | return isLoggedIn ? : ;
525 | }
526 | ```
527 | ## 40) How do you handle redirection in React?
528 | - Use the Navigate component to redirect users programmatically.
529 |
530 | #### Example:
531 |
532 | ```bash
533 | import { Navigate } from 'react-router-dom';
534 |
535 | function Protected({ isLoggedIn }) {
536 | return isLoggedIn ? : ;
537 | }
538 | ```
539 | ## 41) What are dynamic routes in React Router?
540 | - Dynamic routes contain variables that match parts of the URL.
541 |
542 | #### Example:
543 |
544 | ```bash
545 | } />;
546 | ```
547 | - Here, :userId is a dynamic segment.
548 |
549 | ## 42) How do you add default routes in a React app?
550 | - Use the index attribute for default nested routes or specify a catch-all fallback route.
551 |
552 | #### Example:
553 |
554 | ```bash
555 |
556 | }>
557 | } />
558 | } />
559 |
560 |
561 | ```
562 | - Navigating to / renders Home.
563 |
564 | ## 43) What is the significance of exact routes in React Router?
565 | - exact ensures the route matches the path precisely, preventing partial matches. It was used in React Router v5 but is no longer needed in v6 due to improved matching logic.
566 |
567 | - React Router v5 Example:
568 |
569 | ```bash
570 |
571 |
572 | ```
573 | ## 44) How do you handle 404 pages in React?
574 | - Use a catch-all route with a wildcard * path to display a 404 page for unmatched routes.
575 |
576 | #### Example:
577 |
578 | ```
579 |
580 | } />
581 | } />
582 | } />
583 |
584 | ```
585 | - Navigating to a nonexistent route will render the NotFound component.
586 |
587 | ## 45) What are React hooks, and why were they introduced?
588 | - React hooks are functions introduced in React 16.8 to allow functional components to use state and lifecycle features, which were previously only available in class components. They make code cleaner, reduce boilerplate, and promote better organization of logic through reusable custom hooks.
589 |
590 | #### Why Introduced?
591 | - Simplify state management in functional components.
592 | - Encourage sharing logic without complex patterns like higher-order components (HOCs).
593 | - Eliminate the need for classes.
594 | #### Example:
595 |
596 | ```bash
597 | import React, { useState } from 'react';
598 |
599 | function Counter() {
600 | const [count, setCount] = useState(0); // Declare a state variable and its updater function
601 |
602 | return (
603 |
604 |
Count: {count}
605 |
606 |
607 | );
608 | }
609 | ```
610 | - Here, useState allows us to add state to a functional component, simplifying the implementation.
611 | ## 46) What is the difference between useState and useReducer?
612 | |Feature| useState| useReducer| |
613 | |------| ----|----------|-
614 | Purpose| Manage simple states.| Manage complex states with logic.
615 | Syntax| const [state, setState] = useState();| const [state, dispatch] = useReducer();
616 | Usage| For counters, toggles, etc. |For forms, app-level states, etc.|
617 | Example| Increment a counter.| Handle complex state changes with actions.
618 |
619 | #### Example for useReducer:
620 |
621 | ```bash
622 | import React, { useReducer } from 'react';
623 |
624 | const reducer = (state, action) => {
625 | switch (action.type) {
626 | case 'increment': return state + 1;
627 | case 'decrement': return state - 1;
628 | default: return state;
629 | }
630 | };
631 |
632 | function Counter() {
633 | const [count, dispatch] = useReducer(reducer, 0);
634 |
635 | return (
636 |
637 |
Count: {count}
638 |
639 |
640 |
641 | );
642 | }
643 | ```
644 | - useReducer is ideal for managing state transitions in larger applications.
645 |
646 | ## 47) How does the useRef hook work in React?
647 | - useRef provides a way to persist values or references across renders without triggering re-renders. It’s often used for accessing DOM elements or storing mutable values.
648 |
649 | #### Use Cases:
650 | - Access DOM nodes directly.
651 | - Store mutable values that do not trigger re-renders.
652 | #### Example:
653 |
654 | ```bash
655 | import React, { useRef } from 'react';
656 |
657 | function InputFocus() {
658 | const inputRef = useRef(null);
659 |
660 | const handleFocus = () => {
661 | inputRef.current.focus(); // Directly access DOM node
662 | };
663 |
664 | return (
665 |
666 |
667 |
668 |
669 | );
670 | }
671 | ```
672 | - Here, useRef stores a reference to the input element and provides direct access to it.
673 |
674 | ## 48) What is the difference between useEffect and useLayoutEffect?
675 | |Feature | useEffect| useLayoutEffect| |
676 | |------| ----|----------|-
677 | When it Runs| After rendering and painting.| After rendering but before painting.
678 | Use Cases| Data fetching, subscriptions, logging.| DOM manipulations, measurements, animations.
679 | Performance Impact| Less blocking of UI updates.| Blocks painting until work is done.
680 |
681 | #### Example of useLayoutEffect:
682 |
683 | ```bash
684 | import React, { useLayoutEffect, useRef } from 'react';
685 |
686 | function MeasureComponent() {
687 | const divRef = useRef(null);
688 |
689 | useLayoutEffect(() => {
690 | console.log(divRef.current.getBoundingClientRect()); // Accurate measurement
691 | });
692 |
693 | return
Measure Me
;
694 | }
695 | ```
696 | ## 49) How do you optimize performance in React applications?
697 | #### Performance optimization ensures a smoother user experience and faster interactions.
698 |
699 | #### Strategies:
700 | - React.memo: Prevents unnecessary re-renders by memoizing components.
701 | - useCallback and useMemo: Avoids unnecessary re-creation of functions and values.
702 | - Code Splitting: Dynamically loads only required parts of the app.
703 | - Virtualization: Renders only visible items in large lists (e.g., react-window).
704 | - Avoid Reconciliation: Use key attributes and avoid changing component trees unnecessarily.
705 | #### Example with React.memo:
706 |
707 | ```bash
708 | import React from 'react';
709 |
710 | const Child = React.memo(({ data }) => {
711 | console.log('Child re-rendered');
712 | return
723 | );
724 | }
725 | ```
726 | - Here, Child won’t re-render unless its data prop changes.
727 |
728 | ## 50) What is React Context API, and how is it used?
729 | - The Context API allows components to share data without passing props down every level.
730 |
731 | #### Use Cases:
732 | - Global themes.
733 | - User authentication data.
734 | - App-wide configuration.
735 | #### Example:
736 |
737 | ```bash
738 | import React, { createContext, useContext } from 'react';
739 |
740 | const ThemeContext = createContext('light');
741 |
742 | function App() {
743 | return (
744 |
745 |
746 |
747 | );
748 | }
749 |
750 | function Child() {
751 | const theme = useContext(ThemeContext);
752 | return
Current Theme: {theme}
;
753 | }
754 | ````
755 | ## 51) How do you handle global state in React?
756 | - Global state can be managed using tools like the Context API or Redux.
757 |
758 | #### Example with Context API:
759 |
760 | ```bash
761 | const GlobalState = createContext();
762 |
763 | function App() {
764 | const [user, setUser] = useState(null);
765 |
766 | return (
767 |
768 |
769 |
770 | );
771 | }
772 | ```
773 | ## 52) What is Redux, and why is it used with React?
774 | - Redux is a state management library that provides a predictable way to manage state across your application. It ensures the state is centralized, immutable, and debug-friendly.
775 |
776 | #### Core Concepts:
777 | - Store: Single source of truth for application state.
778 | - Action: Describes what to do.
779 | - Reducer: Pure function defining how state changes in response to actions.
780 | ## 53) What are React.lazy and Suspense used for?
781 | - React.lazy enables dynamic import of components for code splitting, while Suspense handles the loading state.
782 |
783 | #### Example:
784 |
785 | ```bash
786 | const LazyComponent = React.lazy(() => import('./LazyComponent'));
787 |
788 | function App() {
789 | return (
790 | Loading...}>
791 |
792 |
793 | );
794 | }
795 | ```
796 | - This setup dynamically loads LazyComponent and shows a fallback until it's ready.
797 |
798 | ## 54)What are the core concepts of Redux?
799 | ### Redux follows three core principles:
800 |
801 | #### Single Source of Truth:
802 | - The entire state of the application is stored in one central location, called the store.
803 | #### Example:
804 |
805 | ```bash
806 | const initialState = { counter: 0 };
807 | const store = createStore(reducer, initialState);
808 | ```
809 |
810 | #### State is Read-Only:
811 | - State can only be changed by dispatching actions, making changes predictable.
812 | #### Example:
813 |
814 | ```bash
815 | store.dispatch({ type: 'INCREMENT' });
816 | ```
817 | #### Changes are Made with Pure Functions (Reducers):
818 | - Reducers are pure functions that take the current state and an action, and return the next state.
819 | #### Example:
820 |
821 | ```bash
822 | function reducer(state = { counter: 0 }, action) {
823 | switch (action.type) {
824 | case 'INCREMENT': return { counter: state.counter + 1 };
825 | default: return state;
826 | }
827 | }
828 | ```
829 | ## 55) What is an action in Redux?
830 | - An action is a plain JavaScript object that describes what happened. It must have a type property that indicates the action's intent.
831 |
832 | #### Example:
833 |
834 | ```bash
835 | const incrementAction = { type: 'INCREMENT' };
836 | store.dispatch(incrementAction);
837 | ```
838 | - Actions can also carry additional data (called payload):
839 |
840 | ```bash
841 | const addTodoAction = { type: 'ADD_TODO', payload: 'Learn Redux' };
842 | ```
843 | ## 56) What is a reducer in Redux?
844 | - A reducer is a pure function that takes the current state and an action, and returns a new state. It specifies how the state should change in response to actions.
845 |
846 | #### Example:
847 |
848 | ```bash
849 | function counterReducer(state = { count: 0 }, action) {
850 | switch (action.type) {
851 | case 'INCREMENT': return { count: state.count + 1 };
852 | case 'DECREMENT': return { count: state.count - 1 };
853 | default: return state;
854 | }
855 | }
856 | ```
857 | ## 57) Explain the role of the Redux store.
858 | - The store holds the entire application state. It provides methods to:
859 |
860 | - Get the current state (store.getState()).
861 | - Dispatch actions (store.dispatch(action)).
862 | - Subscribe to state changes (store.subscribe(callback)).
863 | #### Example:
864 |
865 | ```bash
866 | import { createStore } from 'redux';
867 |
868 | const store = createStore(counterReducer);
869 | store.subscribe(() => console.log(store.getState()));
870 |
871 | store.dispatch({ type: 'INCREMENT' }); // Logs: { count: 1 }
872 | ```
873 | ## 58) How do you connect Redux with React components?
874 | - Use the connect function from react-redux to map the Redux state and dispatch to React component props.
875 |
876 | #### Example:
877 |
878 | ```bash
879 | import { connect } from 'react-redux';
880 |
881 | function Counter({ count, increment }) {
882 | return (
883 |
884 |
Count: {count}
885 |
886 |
887 | );
888 | }
889 |
890 | const mapStateToProps = (state) => ({ count: state.count });
891 | const mapDispatchToProps = (dispatch) => ({
892 | increment: () => dispatch({ type: 'INCREMENT' }),
893 | });
894 |
895 | export default connect(mapStateToProps, mapDispatchToProps)(Counter);
896 | ```
897 | ## 59) What is middleware in Redux?
898 | - Middleware allows you to customize and extend Redux's behavior. It sits between the action dispatch and the reducer, enabling features like logging, asynchronous actions, or API calls.
899 |
900 | #### Example with Redux Thunk:
901 |
902 | ```bash
903 | const loggerMiddleware = (store) => (next) => (action) => {
904 | console.log('Dispatching:', action);
905 | next(action);
906 | };
907 | ```
908 | ## 60) Explain the purpose of mapStateToProps and mapDispatchToProps.
909 | - mapStateToProps: Maps Redux state to component props.
910 | #### Example:
911 |
912 | ```bash
913 | const mapStateToProps = (state) => ({ count: state.count });
914 | ```
915 | - mapDispatchToProps: Maps dispatch functions to component props.
916 | #### Example:
917 |
918 | ```bash
919 | const mapDispatchToProps = (dispatch) => ({
920 | increment: () => dispatch({ type: 'INCREMENT' }),
921 | });
922 | ```
923 | ## 61) What are thunks in Redux?
924 | - A thunk is a middleware function that allows you to write asynchronous logic that interacts with the Redux store. With Redux Thunk, actions can return functions instead of objects.
925 |
926 | - Example with Redux Thunk:
927 |
928 | ```bash
929 | const fetchData = () => {
930 | return async (dispatch) => {
931 | dispatch({ type: 'FETCH_START' });
932 | const data = await fetch('/api/data').then((res) => res.json());
933 | dispatch({ type: 'FETCH_SUCCESS', payload: data });
934 | };
935 | };
936 | ```
937 | ## 62) How do you handle asynchronous actions in Redux?
938 | - You handle asynchronous actions using middleware like Redux Thunk or Redux Saga. These middleware tools enable actions to perform async operations before dispatching.
939 |
940 | #### Example with Thunk:
941 |
942 | ```bash
943 | store.dispatch(fetchData());
944 | ```
945 |
946 | ## 63) How do you implement error boundaries in React?
947 | - Error boundaries are used to catch JavaScript errors in child components and display a fallback UI instead of crashing the entire app. They catch rendering errors, lifecycle method errors, and errors thrown in constructors.
948 |
949 | #### Example Implementation:
950 |
951 | ```bash
952 | class ErrorBoundary extends React.Component {
953 | constructor(props) {
954 | super(props);
955 | this.state = { hasError: false };
956 | }
957 |
958 | static getDerivedStateFromError(error) {
959 | return { hasError: true }; // Update state so the next render shows fallback UI.
960 | }
961 |
962 | componentDidCatch(error, errorInfo) {
963 | // Log error details, e.g., to a monitoring service.
964 | console.error("Error caught by boundary:", error, errorInfo);
965 | }
966 |
967 | render() {
968 | if (this.state.hasError) {
969 | return
Something went wrong.
;
970 | }
971 | return this.props.children;
972 | }
973 | }
974 |
975 | // Usage
976 |
977 |
978 |
979 | ```
980 | - Error boundaries only work in class components, not in functional components.
981 |
982 | ## 64) What is React Fiber?
983 | - React Fiber is React’s reconciliation engine introduced in version 16. It optimizes rendering by dividing the rendering process into small chunks, enabling React to pause, prioritize, and resume work efficiently.
984 |
985 | #### Features of Fiber:
986 |
987 | - Time-slicing: Improves rendering for high-priority tasks.
988 | - Concurrency: Manages animations and transitions smoothly.
989 | ## 65) Explain reconciliation in React.
990 | - Reconciliation is React’s algorithm for efficiently updating the DOM. React creates a Virtual DOM and compares it with the previous state (diffing). Only the differences are updated in the real DOM.
991 |
992 | - Example: If a button’s text changes from "Click Me" to "Clicked", React:
993 |
994 | - Creates a new Virtual DOM tree.
995 | - Finds the difference (text change).
996 | - Updates only the text node instead of re-rendering the entire DOM tree.
997 | ## 66) How does React handle hydration?
998 | - Hydration happens in server-side rendering (SSR). It’s when React takes over static HTML from the server and attaches event listeners to make it interactive.
999 |
1000 | #### Example:
1001 |
1002 | ```bash
1003 | ReactDOM.hydrate(, document.getElementById('root'));
1004 | ```
1005 | - Hydration is efficient because it reuses the server-rendered DOM structure instead of rebuilding it.
1006 |
1007 | ## 67) What is server-side rendering (SSR) in React?
1008 | - In SSR, the React app is rendered on the server, and the generated HTML is sent to the client. This improves SEO and initial load performance.
1009 |
1010 | #### Example (Next.js):
1011 |
1012 | ```bash
1013 | export async function getServerSideProps() {
1014 | const data = await fetch('https://api.example.com');
1015 | return { props: { data } };
1016 | }
1017 |
1018 | export default function Page({ data }) {
1019 | return
{data.message}
;
1020 | }
1021 | ```
1022 | ## 68) What is static site generation (SSG) in React?
1023 | - SSG pre-builds static HTML pages at build time. It’s suitable for content that rarely changes (e.g., blogs).
1024 |
1025 | #### Example (Next.js):
1026 |
1027 | ```
1028 | export async function getStaticProps() {
1029 | const data = await fetch('https://api.example.com');
1030 | return { props: { data } };
1031 | }
1032 |
1033 | export default function Page({ data }) {
1034 | return
{data.message}
;
1035 | }
1036 | ```
1037 | ## 69) What are React Suspense and Concurrent Mode?
1038 | - Suspense: Allows React to "suspend" rendering until some asynchronous data (like a lazy-loaded component) is ready.
1039 | - Concurrent Mode: Enhances performance by breaking tasks into smaller units and prioritizing them.
1040 | #### Example of Suspense:
1041 |
1042 | ```bash
1043 | import React, { Suspense, lazy } from 'react';
1044 |
1045 | const LazyComponent = lazy(() => import('./LazyComponent'));
1046 |
1047 | function App() {
1048 | return (
1049 | Loading...}>
1050 |
1051 |
1052 | );
1053 | }
1054 | ```
1055 | ## 70) How do you implement pagination in React?
1056 | - Pagination divides data into pages, allowing users to navigate through them.
1057 |
1058 | #### Example:
1059 |
1060 | ```bash
1061 | const itemsPerPage = 5;
1062 | const [currentPage, setCurrentPage] = useState(1);
1063 | const currentItems = data.slice(
1064 | (currentPage - 1) * itemsPerPage,
1065 | currentPage * itemsPerPage
1066 | );
1067 |
1068 | return (
1069 |
1070 | {currentItems.map(item => (
1071 |
{item.name}
1072 | ))}
1073 |
1074 |
1075 |
1076 | );
1077 | ```
1078 |
1079 | ## 71) How do you implement infinite scrolling in React?
1080 | - Infinite scrolling loads more data when the user scrolls near the bottom of the page.
1081 |
1082 | #### Example:
1083 |
1084 | ```bash
1085 | useEffect(() => {
1086 | const handleScroll = () => {
1087 | if (window.innerHeight + document.documentElement.scrollTop >= document.documentElement.offsetHeight) {
1088 | loadMoreData();
1089 | }
1090 | };
1091 | window.addEventListener('scroll', handleScroll);
1092 | return () => window.removeEventListener('scroll', handleScroll);
1093 | }, []);
1094 | ```
1095 | ## 72) What is the purpose of the useCallback hook?
1096 | - useCallback memoizes a function to avoid unnecessary re-creations during re-renders.
1097 |
1098 | #### Example:
1099 |
1100 | ```bash
1101 | const memoizedFunction = useCallback(() => {
1102 | doSomething();
1103 | }, [dependency]);
1104 | ```
1105 | ## 73) How does the useMemo hook work in React?
1106 | - useMemo memoizes the result of a computation to optimize performance.
1107 |
1108 | #### Example:
1109 |
1110 | ```bash
1111 | const computedValue = useMemo(() => expensiveCalculation(data), [data]);
1112 | ```
1113 | ## 74) What are custom hooks in React? Provide an example.
1114 | - Custom hooks encapsulate reusable logic.
1115 |
1116 | #### Example:
1117 |
1118 | ```bash
1119 | function useFetch(url) {
1120 | const [data, setData] = useState(null);
1121 |
1122 | useEffect(() => {
1123 | fetch(url).then((res) => res.json()).then(setData);
1124 | }, [url]);
1125 |
1126 | return data;
1127 | }
1128 |
1129 | const data = useFetch('/api/data');
1130 | ```
1131 | ## 75) How do you handle authentication in React?
1132 | - Use libraries like Firebase, Auth0, or JWT for authentication. Store tokens in cookies or local storage and validate them on requests.
1133 |
1134 | ## 76) What are JWTs, and how do they work in React?
1135 | - JWTs (JSON Web Tokens) are a compact, self-contained way to represent authentication information.
1136 |
1137 | #### Example:
1138 |
1139 | - After login, the server issues a JWT.
1140 | - The client stores the token and includes it in headers for authenticated requests.
1141 | ```bash
1142 | fetch('/protected', {
1143 | headers: { Authorization: `Bearer ${token}` }
1144 | });
1145 | ```
1146 | ## 77) How do you implement role-based access control in React?
1147 | - Check roles before rendering components.
1148 |
1149 | #### Example:
1150 |
1151 | ```bash
1152 | function ProtectedComponent({ role }) {
1153 | return role === 'admin' ? : ;
1154 | }
1155 | ```
1156 | ## 78) How do you implement drag-and-drop in React?
1157 | - Use libraries like react-dnd or HTML5 drag-and-drop API.
1158 |
1159 | #### Example:
1160 |
1161 | ```bash
1162 |
Drag Me
1163 | ```
1164 |
1165 | ## 79) How do you debug React applications?
1166 | - React DevTools: Inspect the component tree and props/state.
1167 | - Console logs: Use console.log() for debugging specific values.
1168 | - Error boundaries: Catch errors in rendering or lifecycle methods.
1169 | - Debugger: Use the browser's debugging tools or debugger keyword in your code.
1170 | - Profiler: Analyze rendering performance with React DevTools.
1171 | ## 80) What tools are commonly used to test React applications?
1172 | - Jest: For unit testing.
1173 | - React Testing Library: For component testing.
1174 | - Cypress: For end-to-end testing.
1175 | - Enzyme: For shallow and full rendering tests.
1176 |
1177 |
1178 |
1179 | ## 81) How do you implement error boundaries in React?
1180 | - Error boundaries catch JavaScript errors in their child components, preventing crashes and displaying fallback UIs instead.
1181 |
1182 | #### Key Points:
1183 | - Can only catch errors in the rendering phase, lifecycle methods, and constructors.
1184 | - Cannot catch errors in event handlers.
1185 | #### Example:
1186 | ```bash
1187 | class ErrorBoundary extends React.Component {
1188 | constructor(props) {
1189 | super(props);
1190 | this.state = { hasError: false };
1191 | }
1192 |
1193 | static getDerivedStateFromError(error) {
1194 | // Update state to show fallback UI
1195 | return { hasError: true };
1196 | }
1197 |
1198 | componentDidCatch(error, info) {
1199 | // Log the error (optional)
1200 | console.error("Error:", error, "Info:", info);
1201 | }
1202 |
1203 | render() {
1204 | if (this.state.hasError) {
1205 | return
Something went wrong.
;
1206 | }
1207 | return this.props.children;
1208 | }
1209 | }
1210 |
1211 | // Usage
1212 |
1213 |
1214 |
1215 | ```
1216 | ## 82) What is React Fiber?
1217 | - React Fiber is the reimplementation of React’s rendering engine, introduced in React 16. It makes updates faster and smoother.
1218 |
1219 | #### Key Features:
1220 | - Time-Slicing: Breaks rendering work into chunks for smooth UI rendering.
1221 | - Concurrency: Enables React to handle updates like animations and user input efficiently.
1222 | #### Example:
1223 | - React Fiber improves scenarios where frequent updates, like typing or animations, happen.
1224 |
1225 | ## 83) Explain reconciliation in React.
1226 | - Reconciliation is React’s process for determining what changes are needed in the DOM. It uses a diffing algorithm to identify minimal updates.
1227 |
1228 | #### Example:
1229 | - If a button changes its text:
1230 |
1231 | ```bash
1232 | function App() {
1233 | return ;
1234 | }
1235 | // Updated to:
1236 | function App() {
1237 | return ;
1238 | }
1239 | // React only updates the button's text instead of re-rendering the entire component.
1240 | ```
1241 | ## 84) How does React handle hydration?
1242 | - Hydration happens when React attaches event listeners to server-rendered HTML. It’s common in Server-Side Rendering (SSR) to make the static HTML interactive.
1243 |
1244 | #### Example:
1245 | ```bash
1246 | ReactDOM.hydrate(, document.getElementById('root'));
1247 | ```
1248 | #### Why Use Hydration?
1249 | - It improves page load speed while still providing React’s interactivity.
1250 |
1251 | ## 85) What is server-side rendering (SSR) in React?
1252 | - SSR generates the initial HTML on the server, sending it to the browser for rendering. It improves SEO and reduces the time for the page to display.
1253 |
1254 | #### Example (Next.js):
1255 | ```bash
1256 | export async function getServerSideProps() {
1257 | const data = await fetch('/api/data');
1258 | return { props: { data } };
1259 | }
1260 |
1261 | function Page({ data }) {
1262 | return
{data}
;
1263 | }
1264 | ```
1265 | ## 86) How does SSR differ from client-side rendering (CSR)?
1266 | ### SSR
1267 | - Initial HTML is generated on the server.
1268 | - Faster initial load time.
1269 | - Better SEO.
1270 | ### CSR
1271 | - HTML is generated in the browser via JavaScript.
1272 | - Slower initial load but faster subsequent interactions.
1273 | - SEO may require extra configuration.
1274 | ## 87) What is static site generation (SSG) in React?
1275 | - SSG pre-renders pages at build time, creating static HTML files. It’s faster than SSR for content that rarely changes.
1276 |
1277 | #### Example (Next.js):
1278 | ```bash
1279 | export async function getStaticProps() {
1280 | const data = await fetch('/api/data');
1281 | return { props: { data } };
1282 | }
1283 |
1284 | function Page({ data }) {
1285 | return
{data}
;
1286 | }
1287 | ```
1288 | ## 88) What are React Suspense and Concurrent Mode?
1289 | - Suspense: Allows React to wait for asynchronous operations (like lazy loading) and show a fallback UI.
1290 | - Concurrent Mode: Improves responsiveness by letting React handle multiple tasks simultaneously.
1291 | #### Example with Suspense:
1292 | ```bash
1293 | const LazyComponent = React.lazy(() => import('./MyComponent'));
1294 |
1295 | Loading...}>
1296 |
1297 |
1298 | ```
1299 | ## 89) How do you implement pagination in React?
1300 | - Pagination splits data into smaller chunks for easier navigation.
1301 |
1302 | #### Example:
1303 | ```bash
1304 | function PaginatedList({ items, itemsPerPage }) {
1305 | const [currentPage, setCurrentPage] = useState(1);
1306 | const startIndex = (currentPage - 1) * itemsPerPage;
1307 | const currentItems = items.slice(startIndex, startIndex + itemsPerPage);
1308 |
1309 | return (
1310 |
1311 | {currentItems.map((item) => (
1312 |
{item.name}
1313 | ))}
1314 |
1315 |
1316 |
1317 | );
1318 | }
1319 | ```
1320 | ## 90)How do you test React components using Jest?
1321 |
1322 | - Jest is a JavaScript testing framework used for unit tests, integration tests, and snapshots in React applications.
1323 |
1324 | #### Testing React Components:
1325 | - Use Jest with @testing-library/react for rendering components and testing their behavior.
1326 | #### Example:
1327 | ```bash
1328 | import { render, screen } from '@testing-library/react';
1329 | import userEvent from '@testing-library/user-event';
1330 | import Button from './Button';
1331 |
1332 | test('renders the button and checks click event', () => {
1333 | const handleClick = jest.fn();
1334 | render();
1335 |
1336 | // Assert text is rendered
1337 | expect(screen.getByText('Click Me')).toBeInTheDocument();
1338 |
1339 | // Simulate click event
1340 | userEvent.click(screen.getByText('Click Me'));
1341 | expect(handleClick).toHaveBeenCalledTimes(1);
1342 | });
1343 | ```
1344 |
1345 | ## 91) What is the purpose of Enzyme in React testing?
1346 | #### Purpose:
1347 | - Enzyme, developed by Airbnb, is a React testing library that allows testing React components' output, state, and behavior. It provides shallow rendering, full DOM rendering, and static rendering.
1348 |
1349 | #### Example:
1350 | ```bash
1351 | import { shallow } from 'enzyme';
1352 | import App from './App';
1353 |
1354 | test('renders header', () => {
1355 | const wrapper = shallow();
1356 | expect(wrapper.find('h1').text()).toEqual('Welcome to My App');
1357 | });
1358 | ```
1359 | #### Key Difference:
1360 | - While Enzyme tests specific component internals, React Testing Library focuses on user behavior.
1361 |
1362 | ## 92) How do you implement Snapshot testing in React?
1363 | #### Snapshot Testing Overview:
1364 | - Snapshot testing ensures UI consistency by comparing the rendered output of a component to a saved "snapshot".
1365 |
1366 | #### Example:
1367 | ```bash
1368 | import { render } from '@testing-library/react';
1369 | import Header from './Header';
1370 |
1371 | test('renders correctly', () => {
1372 | const { asFragment } = render();
1373 | expect(asFragment()).toMatchSnapshot();
1374 | });
1375 | ```
1376 | - When changes occur, the test fails, prompting you to update the snapshot.
1377 |
1378 | ## 93) How do you integrate TypeScript with React?
1379 | #### Steps:
1380 | - Install TypeScript and type definitions:
1381 |
1382 | ```bash
1383 | npm install typescript @types/react @types/react-dom
1384 | ```
1385 | - Rename .js files to .tsx.
1386 |
1387 | - Add a tsconfig.json:
1388 |
1389 | ```bash
1390 | {
1391 | "compilerOptions": {
1392 | "jsx": "react",
1393 | "strict": true
1394 | }
1395 | }
1396 | ```
1397 | #### Example:
1398 | ```bash
1399 | type Props = { message: string };
1400 |
1401 | const Greeting: React.FC = ({ message }) =>
{message}
;
1402 | ```
1403 | ## 94) What are the benefits of using TypeScript in React projects?
1404 | - Type Safety: Prevents runtime errors by catching type issues during development.
1405 | - Better Developer Experience: Autocompletion, better refactoring, and clear documentation.
1406 | - Early Bug Detection: Errors are identified at compile time.
1407 | - Improved Code Readability: Types make the codebase easier to understand.
1408 |
1409 | ## 95) How do you manage environment variables in React?
1410 | #### Steps:
1411 | - Create a .env file in the root directory:
1412 |
1413 | ```bash
1414 | REACT_APP_API_URL=https://api.example.com
1415 | ```
1416 | - Access the variable in your code:
1417 |
1418 | ```bash
1419 | console.log(process.env.REACT_APP_API_URL);
1420 | ```
1421 |
1422 |
1423 | ## 96) How do you implement a theme switcher (dark mode) in React?
1424 | #### Example:
1425 | ```bash
1426 | import { useState } from 'react';
1427 |
1428 | function App() {
1429 | const [theme, setTheme] = useState('light');
1430 |
1431 | return (
1432 |
1433 |
1436 |
1437 | );
1438 | }
1439 | ```
1440 | #### CSS:
1441 |
1442 | ```bash
1443 | .light { background: white; color: black; }
1444 | .dark { background: black; color: white; }
1445 | ```
1446 |
1447 | ## 97) How do you handle file uploads in React?
1448 | #### Example:
1449 | ```bash
1450 | function FileUpload() {
1451 | const handleUpload = (event) => {
1452 | const file = event.target.files[0];
1453 | const formData = new FormData();
1454 | formData.append('file', file);
1455 |
1456 | fetch('/upload', { method: 'POST', body: formData });
1457 | };
1458 |
1459 | return ;
1460 | }
1461 | ```
1462 | ## 98)How do you implement routing in React applications?
1463 |
1464 | - Routing in React is managed using libraries like React Router, allowing navigation between different components or pages without refreshing the browser.
1465 |
1466 | #### Example:
1467 | - Install React Router:
1468 |
1469 | ```bash
1470 | npm install react-router-dom
1471 | ```
1472 | - Set up routing in your app:
1473 |
1474 | ```bash
1475 | import { BrowserRouter, Routes, Route } from 'react-router-dom';
1476 | import Home from './Home';
1477 | import About from './About';
1478 |
1479 | function App() {
1480 | return (
1481 |
1482 |
1483 | } />
1484 | } />
1485 |
1486 |
1487 | );
1488 | }
1489 |
1490 | export default App;
1491 | ```
1492 | #### Here:
1493 |
1494 | - / renders the Home component.
1495 | - /about renders the About component.
1496 | ## 99) What is the role of the component in React Router?
1497 |
1498 | - In React Router v5, was used to render the first child that matches the URL. It ensures only one route is rendered at a time.
1499 |
1500 | #### Example:
1501 | ```bash
1502 | import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
1503 |
1504 | function App() {
1505 | return (
1506 |
1507 |
1508 |
1509 |
1510 |
1511 |
1512 | );
1513 | }
1514 | ```
1515 | - If the path is /about, the About component is rendered.
1516 | React Router v6 replaces with .
1517 | ## 100) How do you implement private routes in React?
1518 |
1519 | - Private routes restrict access to specific components/pages based on authentication.
1520 |
1521 | #### Example:
1522 | ```bash
1523 | import { Navigate } from 'react-router-dom';
1524 |
1525 | function PrivateRoute({ children }) {
1526 | const isAuthenticated = !!localStorage.getItem('token'); // Example check
1527 |
1528 | return isAuthenticated ? children : ;
1529 | }
1530 |
1531 | function App() {
1532 | return (
1533 |
1534 |
1535 | } />
1536 |
1540 |
1541 |
1542 | }
1543 | />
1544 |
1545 |
1546 | );
1547 | }
1548 | ```
1549 |
1550 | - If the user is authenticated, they access the Dashboard.
1551 | - Otherwise, they are redirected to /login.
1552 |
1553 |
1554 | ## 101) What is React StrictMode?
1555 |
1556 | - React.StrictMode is a tool for highlighting potential problems in a React app. It doesn’t render anything visible to the UI but activates additional checks and warnings for its child components.
1557 |
1558 | ### Features:
1559 | - Detects unsafe lifecycle methods.
1560 | - Warns about using deprecated APIs.
1561 | - Highlights side effects in useEffect.
1562 | #### Example:
1563 | ```bash
1564 | import React from 'react';
1565 | import ReactDOM from 'react-dom';
1566 | import App from './App';
1567 |
1568 | ReactDOM.render(
1569 |
1570 |
1571 | ,
1572 | document.getElementById('root')
1573 | );
1574 | ```
1575 | ## 102) What is the difference between the useState and useReducer hooks?
1576 | | useState|useReducer |||
1577 | |------| ----|-------|-
1578 | |Simpler API for managing local state. |Better for complex state logic.
1579 | Returns state and a state updater function. |Returns state and a dispatch function.
1580 | Suitable for simple toggles, counters, etc. |Suitable for managing multiple related state updates.
1581 |
1582 | #### Example:
1583 | - Using useState:
1584 |
1585 | ```bash
1586 | const [count, setCount] = useState(0);
1587 |
1588 | ;
1589 | ```
1590 | - Using useReducer:
1591 |
1592 | ```bash
1593 | const reducer = (state, action) => {
1594 | switch (action.type) {
1595 | case 'increment': return state + 1;
1596 | case 'decrement': return state - 1;
1597 | default: return state;
1598 | }
1599 | };
1600 |
1601 | const [count, dispatch] = useReducer(reducer, 0);
1602 |
1603 | ;
1604 | ```
1605 | ## 103) How does the useContext hook work?
1606 |
1607 | - The useContext hook allows you to consume values from a React Context in functional components without using Consumer.
1608 |
1609 | #### Example:
1610 | ```bash
1611 | const ThemeContext = React.createContext('light');
1612 |
1613 | function App() {
1614 | return (
1615 |
1616 |
1617 |
1618 | );
1619 | }
1620 |
1621 | function Toolbar() {
1622 | const theme = useContext(ThemeContext);
1623 | return
Current theme: {theme}
;
1624 | }
1625 | ```
1626 | ## 104) What is a compound component pattern in React?
1627 |
1628 | - Compound components let you build reusable components where the parent component manages the state and logic while child components share this state.
1629 |
1630 | #### Example:
1631 | ```bash
1632 | function Tabs({ children }) {
1633 | const [activeIndex, setActiveIndex] = useState(0);
1634 |
1635 | return (
1636 |
2131 | ```
2132 | ## 130) What is the difference between React.PureComponent and React.Component?
2133 |
2134 | - React.Component: Re-renders every time props or state change, regardless of whether the changes are meaningful.
2135 | - React.PureComponent: Implements a shallow comparison of props and state, re-rendering only when meaningful changes occur.
2136 | #### Example:
2137 | ```bash
2138 | import React, { Component, PureComponent } from 'react';
2139 |
2140 | class RegularComponent extends Component {
2141 | render() {
2142 | console.log('Regular Component Rendered');
2143 | return
;
2521 | }
2522 | ```
2523 | ## 145) How do you optimize React app performance?
2524 | - Use React.memo to prevent unnecessary re-renders.
2525 | - Use useCallback and useMemo for performance optimizations.
2526 | - Lazy Load Components.
2527 | - Optimize API calls using React Query.
2528 | ## 146) What are React Fragments?
2529 |
2530 | - Allows grouping elements without an extra DOM node.
2531 |
2532 | ### Example:
2533 | ```bash
2534 | function App() {
2535 | return (
2536 | <>
2537 |
Title
2538 |
Some text
2539 | >
2540 | );
2541 | }
2542 | ```
2543 | ## 147) How does React handle keys in lists?
2544 | - Keys help React identify changes in lists for efficient updates.
2545 |
2546 | ### Example:
2547 | ```bash
2548 | const items = ["Apple", "Banana", "Cherry"];
2549 |
2550 | function List() {
2551 | return (
2552 |
2553 | {items.map((item, index) => (
2554 |
{item}
// Bad practice, use unique ID if possible
2555 | ))}
2556 |
2557 | );
2558 | }
2559 | ```
2560 | ## 148) How does reconciliation work in React?
2561 | - React uses a Virtual DOM and a diffing algorithm to update only the necessary parts of the UI.
2562 |
2563 | ## 149) What is the difference between useState and useEffect?
2564 | | Feature | useState | useEffect |
2565 | |----------|----------------------------------------|-------------------------------------|
2566 | | Purpose | Manage component state | Perform side effects |
2567 | | Runs | When state updates | After render |
2568 | | Example | `const [count, setCount] = useState(0);` | `useEffect(() => { fetchData(); }, []);` |
2569 |
2570 | ## 149) What are compound components in React?
2571 |
2572 | - A pattern where multiple components work together within a parent.
2573 |
2574 | ### Example:
2575 | ```bash
2576 | function Modal({ children }) {
2577 | return