└── 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 | ; 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 |
    194 | setName(e.target.value)} /> 195 | 196 |
    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

    Hello

    ; 322 | } 323 | } 324 | ``` 325 | ## 26) Explain the significance of React.StrictMode. 326 | - StrictMode highlights potential problems in an application by running additional checks and warnings in development mode. 327 | #### Example: 328 | 329 | ```bash 330 | 331 | 332 | 333 | ``` 334 | ## 27) How does React handle conditional rendering? 335 | #### React handles conditional rendering using: 336 | 337 | - Ternary operators 338 | - Logical && operator 339 | - If-else statements 340 | #### Example: 341 | 342 | ```bash 343 | function App({ isLoggedIn }) { 344 | return isLoggedIn ?

    Welcome

    :

    Please Log In

    ; 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 |
    Portal Content
    , 369 | document.getElementById('portal-root') 370 | ); 371 | ``` 372 | ## 30) Explain lazy loading in React. 373 | - Lazy loading delays loading components until they’re needed, improving performance. 374 | #### Example: 375 | 376 | ```bash 377 | const LazyComponent = lazy(() => import('./LazyComponent')); 378 | function App() { 379 | return ( 380 | Loading...}> 381 | 382 | 383 | ); 384 | } 385 | ``` 386 | ## 31) What is React.memo, and why is it used? 387 | - React.memo prevents unnecessary re-renders by memoizing the component unless its props change. 388 | #### Example: 389 | 390 | ```bash 391 | const MemoizedComponent = React.memo(({ count }) => { 392 | console.log('Rendered'); 393 | return
    {count}
    ; 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

    Home Page

    ; 476 | } 477 | 478 | function About() { 479 | return

    About Page

    ; 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

    {data}

    ; 713 | }); 714 | 715 | function Parent() { 716 | const [count, setCount] = React.useState(0); 717 | 718 | return ( 719 |
    720 | 721 | 722 |
    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 |
    1637 | {React.Children.map(children, (child, index) => 1638 | React.cloneElement(child, { 1639 | isActive: activeIndex === index, 1640 | onClick: () => setActiveIndex(index), 1641 | }) 1642 | )} 1643 |
    1644 | ); 1645 | } 1646 | 1647 | function Tab({ isActive, onClick, children }) { 1648 | return ; 1649 | } 1650 | 1651 | function App() { 1652 | return ( 1653 | 1654 | Tab 1 1655 | Tab 2 1656 | Tab 3 1657 | 1658 | ); 1659 | } 1660 | ``` 1661 | ## 105) How do you create a reusable component in React? 1662 | 1663 | - Reusable components are designed to work in multiple contexts by accepting props to customize their behavior and appearance. 1664 | 1665 | #### Example: 1666 | ```bash 1667 | function Button({ children, onClick, variant = 'primary' }) { 1668 | const style = variant === 'primary' ? 'btn-primary' : 'btn-secondary'; 1669 | 1670 | return ( 1671 | 1674 | ); 1675 | } 1676 | 1677 | // Usage 1678 | 1679 | 1680 | ``` 1681 | - This Button component can be reused across different parts of the app by changing props like variant or onClick. 1682 | 1683 | ## 106)How would you optimize rendering performance in React? 1684 | 1685 | - Optimizing performance involves avoiding unnecessary renders and reducing DOM updates. 1686 | 1687 | ### Techniques: 1688 | - React.memo: Prevents unnecessary renders for functional components. 1689 | - useCallback and useMemo: Optimize inline functions and computed values. 1690 | - Code splitting: Load components on demand using React.lazy. 1691 | - Virtualization: Render only visible items in a list (e.g., using react-window). 1692 | - Avoid anonymous functions: Use memoized callbacks to prevent re-renders. 1693 | #### Example: 1694 | ```bash 1695 | const Button = React.memo(({ onClick, children }) => { 1696 | console.log('Button rendered'); 1697 | return ; 1698 | }); 1699 | 1700 | function App() { 1701 | const [count, setCount] = React.useState(0); 1702 | const increment = React.useCallback(() => setCount((c) => c + 1), []); 1703 | return ( 1704 |
    1705 | 1706 |
    1707 | ); 1708 | } 1709 | ``` 1710 | ## 107)How do you manage dependencies in a large React application? 1711 | ### Techniques: 1712 | - Package.json: Maintain all dependencies with clear versioning. 1713 | - Peer dependencies: Define shared dependencies for libraries. 1714 | - Monorepos: Use tools like Lerna for multi-package projects. 1715 | - npm audit: Regularly check for vulnerabilities. 1716 | ## 108) How do you implement animations in React? 1717 | 1718 | - Use libraries like React Spring, Framer Motion, or CSS animations. 1719 | 1720 | #### Example: 1721 | - With Framer Motion: 1722 | 1723 | ```bash 1724 | import { motion } from 'framer-motion'; 1725 | 1726 | function Box() { 1727 | return ( 1728 | 1733 | Animated Box 1734 | 1735 | ); 1736 | } 1737 | ``` 1738 | ## 109)How do you implement a drag-and-drop feature in React? 1739 | 1740 | - Use libraries like react-dnd or react-beautiful-dnd. 1741 | 1742 | - With react-beautiful-dnd: 1743 | 1744 | ```bash 1745 | import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; 1746 | 1747 | const items = [ 1748 | { id: '1', text: 'Item 1' }, 1749 | { id: '2', text: 'Item 2' }, 1750 | ]; 1751 | 1752 | function App() { 1753 | const onDragEnd = (result) => { 1754 | console.log(result); 1755 | }; 1756 | 1757 | return ( 1758 | 1759 | 1760 | {(provided) => ( 1761 |
    1762 | {items.map((item, index) => ( 1763 | 1764 | {(provided) => ( 1765 |
    1766 | {item.text} 1767 |
    1768 | )} 1769 |
    1770 | ))} 1771 | {provided.placeholder} 1772 |
    1773 | )} 1774 |
    1775 |
    1776 | ); 1777 | } 1778 | ``` 1779 | ## 110) What is the role of CSS-in-JS libraries like styled-components in React? 1780 | 1781 | - CSS-in-JS allows you to write scoped CSS directly in JavaScript files, enabling dynamic styling based on props. 1782 | 1783 | #### Example: 1784 | ```bash 1785 | import styled from 'styled-components'; 1786 | 1787 | const Button = styled.button` 1788 | background-color: ${(props) => (props.primary ? 'blue' : 'gray')}; 1789 | color: white; 1790 | padding: 10px; 1791 | `; 1792 | 1793 | ; 1794 | ; 1795 | ``` 1796 | ## 111)What is the difference between PureComponent and React.memo? 1797 | - PureComponent: A class component that performs a shallow comparison of props and state to avoid unnecessary re-renders. 1798 | - React.memo: A higher-order function used with functional components for similar optimization by memoizing the component. 1799 | #### Example: 1800 | - Using PureComponent: 1801 | 1802 | ```bash 1803 | import React, { PureComponent } from 'react'; 1804 | 1805 | class MyComponent extends PureComponent { 1806 | render() { 1807 | console.log('Rendered PureComponent'); 1808 | return
    {this.props.value}
    ; 1809 | } 1810 | } 1811 | ``` 1812 | - Using React.memo: 1813 | 1814 | ```bash 1815 | const MyFunctionalComponent = React.memo(({ value }) => { 1816 | console.log('Rendered Memoized Component'); 1817 | return
    {value}
    ; 1818 | }); 1819 | ``` 1820 | #### Key Difference: 1821 | - PureComponent works with class components. 1822 | - React.memo works with functional components. 1823 | ## 112) How do you use the useImperativeHandle hook? 1824 | - useImperativeHandle customizes the instance value exposed when using React.forwardRef. 1825 | 1826 | #### Example: 1827 | ```bash 1828 | import React, { useRef, forwardRef, useImperativeHandle } from 'react'; 1829 | 1830 | const Input = forwardRef((props, ref) => { 1831 | const inputRef = useRef(); 1832 | 1833 | useImperativeHandle(ref, () => ({ 1834 | focus: () => { 1835 | inputRef.current.focus(); 1836 | }, 1837 | })); 1838 | 1839 | return ; 1840 | }); 1841 | 1842 | function App() { 1843 | const inputRef = useRef(); 1844 | 1845 | return ( 1846 |
    1847 | 1848 | 1849 |
    1850 | ); 1851 | } 1852 | ``` 1853 | ## 113) Explain the use of the React.forwardRef function. 1854 | 1855 | - React.forwardRef allows a parent component to pass a ref to a child component. 1856 | 1857 | #### Example: 1858 | ```bash 1859 | const FancyButton = React.forwardRef((props, ref) => ( 1860 | 1861 | )); 1862 | 1863 | function App() { 1864 | const buttonRef = React.createRef(); 1865 | 1866 | return ( 1867 | Click Me 1868 | ); 1869 | } 1870 | ``` 1871 | ## 114) What is the difference between React.lazy and loadable components? 1872 | 1873 | - React.lazy: Built-in React feature for code splitting via dynamic imports. 1874 | - Loadable Components: A third-party library with additional features like loading indicators or error handling. 1875 | #### Example: 1876 | - React.lazy: 1877 | 1878 | ```bash 1879 | const LazyComponent = React.lazy(() => import('./MyComponent')); 1880 | 1881 | function App() { 1882 | return ( 1883 | Loading...}> 1884 | 1885 | 1886 | ); 1887 | } 1888 | ``` 1889 | - Loadable Components: 1890 | 1891 | ```bash 1892 | import loadable from '@loadable/component'; 1893 | 1894 | const LoadableComponent = loadable(() => import('./MyComponent'), { 1895 | fallback:
    Loading...
    , 1896 | }); 1897 | 1898 | function App() { 1899 | return ; 1900 | } 1901 | ``` 1902 | ## 115) What are some best practices for structuring a React project? 1903 | #### Best Practices: 1904 | - Modular structure: 1905 | ```bash 1906 | src/ 1907 | ├── components/ 1908 | ├── pages/ 1909 | ├── services/ 1910 | ├── redux/ or context/ 1911 | ├── utils/ 1912 | ├── styles/ 1913 | └── App.js 1914 | ``` 1915 | - Reusable components: Break down the UI into small, composable components. 1916 | - Feature-based folders: Organize files by feature for larger apps. 1917 | - State management: Use Context API or Redux for global state. 1918 | - Separate concerns: Keep logic (services) separate from components. 1919 | ## 116) How do you optimize bundle size in React? 1920 | #### Techniques: 1921 | - Code splitting with React.lazy and React.Suspense. 1922 | - Tree shaking to remove unused code. 1923 | - Dynamic imports for rarely used modules. 1924 | - Use libraries like webpack-bundle-analyzer to analyze and reduce bundle size. 1925 | #### Example: 1926 | ```bash 1927 | const LazyComponent = React.lazy(() => import('./LargeComponent')); 1928 | ``` 1929 | ## 117) How do you handle authentication using Firebase in React? 1930 | #### Example: 1931 | - Set up Firebase: 1932 | 1933 | ```bash 1934 | npm install firebase 1935 | ``` 1936 | - Initialize Firebase: 1937 | 1938 | ```bash 1939 | import firebase from 'firebase/app'; 1940 | import 'firebase/auth'; 1941 | 1942 | const firebaseConfig = { apiKey: '...', authDomain: '...' }; 1943 | firebase.initializeApp(firebaseConfig); 1944 | ``` 1945 | - Sign-in Implementation: 1946 | 1947 | ```bash 1948 | const signInWithGoogle = () => { 1949 | const provider = new firebase.auth.GoogleAuthProvider(); 1950 | firebase.auth().signInWithPopup(provider); 1951 | }; 1952 | ``` 1953 | ## 118) How do you set up SSR using Next.js with React? 1954 | #### Example: 1955 | - Fetch data on the server: 1956 | 1957 | ```bash 1958 | export async function getServerSideProps() { 1959 | const res = await fetch('https://api.example.com/data'); 1960 | const data = await res.json(); 1961 | 1962 | return { props: { data } }; 1963 | } 1964 | 1965 | function Page({ data }) { 1966 | return
    {JSON.stringify(data)}
    ; 1967 | } 1968 | 1969 | export default Page; 1970 | ``` 1971 | ## 119) What are React error boundaries, and how do you implement them? 1972 | 1973 | - Error boundaries catch JavaScript errors in their child components. 1974 | 1975 | #### Example: 1976 | ```bash 1977 | class ErrorBoundary extends React.Component { 1978 | state = { hasError: false }; 1979 | 1980 | static getDerivedStateFromError() { 1981 | return { hasError: true }; 1982 | } 1983 | 1984 | componentDidCatch(error, errorInfo) { 1985 | console.error(error, errorInfo); 1986 | } 1987 | 1988 | render() { 1989 | if (this.state.hasError) { 1990 | return

    Something went wrong.

    ; 1991 | } 1992 | return this.props.children; 1993 | } 1994 | } 1995 | ``` 1996 | - Usage: 1997 | 1998 | ```bash 1999 | 2000 | 2001 | 2002 | ``` 2003 | ## 120) How do you monitor performance in a React app? 2004 | #### Tools: 2005 | - React Profiler: Built-in tool to measure rendering performance. 2006 | - Web Vitals: Monitor metrics like FCP, LCP, etc. 2007 | - Third-party libraries: Use tools like Sentry or LogRocket for monitoring. 2008 | 2009 | 2010 | ## 121) What are synthetic events in React? 2011 | 2012 | - Synthetic events are React's wrapper around browser-native events, ensuring cross-browser compatibility. 2013 | 2014 | #### Example: 2015 | ```bash 2016 | function App() { 2017 | const handleClick = (e) => { 2018 | console.log(e.nativeEvent); // Access native event 2019 | console.log(e); // Synthetic event 2020 | }; 2021 | 2022 | return ; 2023 | } 2024 | ``` 2025 | ## 122) How do you avoid memory leaks in React? 2026 | #### Techniques: 2027 | - Cleanup in useEffect: 2028 | 2029 | ```bash 2030 | useEffect(() => { 2031 | const interval = setInterval(() => console.log('Running'), 1000); 2032 | return () => clearInterval(interval); // Cleanup 2033 | }, []); 2034 | ``` 2035 | - Use AbortController to cancel API requests. 2036 | 2037 | ## 123) What are the different lifecycle methods of React? 2038 | 2039 | #### React class components have: 2040 | 2041 | - Mounting: constructor, componentDidMount. 2042 | - Updating: componentDidUpdate. 2043 | - Unmounting: componentWillUnmount. 2044 | - Functional components use hooks for similar functionality. 2045 | 2046 | ## 124) What is Flux architecture? 2047 | 2048 | - Flux is an application architecture for managing unidirectional data flow in React apps. It has: 2049 | 2050 | - Actions: Dispatch actions to update the store. 2051 | - Dispatcher: Central hub for event dispatching. 2052 | - Store: Holds the state. 2053 | - View: React components. 2054 | ## 125) How is Flux different from Redux? 2055 | |Feature| Flux| Redux|| 2056 | |----|----|----|---| 2057 | |Store |Multiple stores |Single store 2058 | |Dispatcher| Central dispatcher| No dispatcher 2059 | |State mutation| Directly in store |Pure reducers 2060 | 2061 | ## 126) How do you use hooks to manage form validation? 2062 | #### Example: 2063 | ```bash 2064 | function App() { 2065 | const [email, setEmail] = React.useState(''); 2066 | const [error, setError] = React.useState(''); 2067 | 2068 | const handleSubmit = (e) => { 2069 | e.preventDefault(); 2070 | if (!email.includes('@')) { 2071 | setError('Invalid email'); 2072 | } else { 2073 | setError(''); 2074 | } 2075 | }; 2076 | 2077 | return ( 2078 |
    2079 | setEmail(e.target.value)} /> 2080 | {error && {error}} 2081 |
    2082 | ); 2083 | } 2084 | ``` 2085 | ## 127) How would you implement caching in a React app? 2086 | #### Techniques: 2087 | - Use localStorage or sessionStorage. 2088 | - Cache API responses with libraries like axios-cache-adapter. 2089 | - Service Workers for offline caching. 2090 | ## 128) What is the purpose of React.cloneElement? 2091 | 2092 | - React.cloneElement clones a React element, optionally modifying its props or children. 2093 | 2094 | #### Example: 2095 | ```bash 2096 | const Button = (props) => ; 2097 | 2098 | const App = () => { 2099 | const clonedButton = React.cloneElement( 2253 | 2254 | ); 2255 | } 2256 | ``` 2257 | ## 134) How do you optimize API calls in React? 2258 | #### Techniques: 2259 | - Debounce/throttle API calls: 2260 | 2261 | ```bash 2262 | import { debounce } from 'lodash'; 2263 | const fetchDebounced = debounce(() => fetchData(), 500); 2264 | ``` 2265 | - Use React Query: 2266 | 2267 | ```bash 2268 | import { useQuery } from 'react-query'; 2269 | 2270 | const { data, isLoading } = useQuery('fetchData', fetchData); 2271 | ``` 2272 | - Cache results in local state or libraries like Redux. 2273 | 2274 | - Avoid unnecessary calls with proper dependency arrays in useEffect. 2275 | 2276 | ## 135) What are the common anti-patterns in React? 2277 | #### Examples of Anti-Patterns: 2278 | - Mutating state directly: 2279 | 2280 | ```bash 2281 | this.state.count = 10; // WRONG 2282 | this.setState({ count: 10 }); // Correct 2283 | ``` 2284 | - Overusing Redux/Context API: 2285 | 2286 | - Avoid managing local component states like form inputs in Redux. 2287 | #### Excessive re-renders: 2288 | 2289 | - Use React.memo or useCallback to avoid unnecessary re-renders. 2290 | - Not cleaning up side effects: 2291 | 2292 | ```bash 2293 | useEffect(() => { 2294 | const interval = setInterval(doSomething, 1000); 2295 | return () => clearInterval(interval); // Cleanup 2296 | }, []); 2297 | ``` 2298 | ## 136) How do you improve SEO in React apps? 2299 | #### Techniques: 2300 | - Server-Side Rendering (SSR) with Next.js: 2301 | 2302 | ```bash 2303 | export async function getServerSideProps() { 2304 | const data = await fetchData(); 2305 | return { props: { data } }; 2306 | } 2307 | ``` 2308 | - Meta tags using libraries like React Helmet: 2309 | 2310 | ```bash 2311 | import { Helmet } from 'react-helmet'; 2312 | 2313 | function App() { 2314 | return ( 2315 | 2316 | My App 2317 | 2318 | 2319 | ); 2320 | } 2321 | ``` 2322 | - Dynamic routing with clear URLs. 2323 | 2324 | - Pre-rendering and static generation. 2325 | 2326 | ## 137) How do you implement a carousel in React? 2327 | ### Example using a library: 2328 | ```bash 2329 | import Carousel from 'react-multi-carousel'; 2330 | import 'react-multi-carousel/lib/styles.css'; 2331 | 2332 | function App() { 2333 | return ( 2334 | 2335 |
    Item 1
    2336 |
    Item 2
    2337 |
    Item 3
    2338 |
    2339 | ); 2340 | } 2341 | ``` 2342 | - Custom Implementation: 2343 | ```bash 2344 | function Carousel({ items }) { 2345 | const [index, setIndex] = React.useState(0); 2346 | 2347 | return ( 2348 |
    2349 | 2350 |
    {items[index]}
    2351 | 2352 |
    2353 | ); 2354 | } 2355 | ``` 2356 | ## 138) How do you handle file uploads in React? 2357 | ### Example: 2358 | - HTML Input and State: 2359 | 2360 | ```bash 2361 | function App() { 2362 | const [file, setFile] = React.useState(null); 2363 | 2364 | const handleFileUpload = (event) => { 2365 | setFile(event.target.files[0]); 2366 | }; 2367 | 2368 | return ; 2369 | } 2370 | ``` 2371 | - Uploading to a Server: 2372 | 2373 | ```bash 2374 | const handleUpload = async () => { 2375 | const formData = new FormData(); 2376 | formData.append('file', file); 2377 | 2378 | const response = await fetch('/upload', { 2379 | method: 'POST', 2380 | body: formData, 2381 | }); 2382 | 2383 | if (response.ok) { 2384 | console.log('File uploaded successfully'); 2385 | } 2386 | }; 2387 | ``` 2388 | - Uploading to Firebase: 2389 | ```bash 2390 | import { storage } from './firebase'; 2391 | 2392 | const uploadToFirebase = () => { 2393 | const storageRef = storage.ref(`files/${file.name}`); 2394 | storageRef.put(file).then(() => { 2395 | console.log('Uploaded to Firebase'); 2396 | }); 2397 | }; 2398 | ``` 2399 | ## 139) How do you design responsive components in React? 2400 | 2401 | ### Responsive components adjust their layout based on screen size. You can achieve this using: 2402 | 2403 | - CSS Media Queries 2404 | - CSS-in-JS libraries like Styled Components 2405 | - Flexbox/Grid 2406 | - Tailwind CSS 2407 | - React libraries like react-responsive 2408 | ### Example (Using Tailwind CSS) 2409 | ```bash 2410 | function ResponsiveCard() { 2411 | return ( 2412 |
    2413 |

    Responsive Component

    2414 |

    This adjusts based on screen size.

    2415 |
    2416 | ); 2417 | } 2418 | ``` 2419 | ## 140) What are controlled and uncontrolled components in React? 2420 | 2421 | - Controlled Component: React controls the state of the input. 2422 | - Uncontrolled Component: The DOM itself maintains the state. 2423 | ### Example (Controlled Component) 2424 | ```bash 2425 | function ControlledInput() { 2426 | const [value, setValue] = React.useState(""); 2427 | 2428 | return setValue(e.target.value)} />; 2429 | } 2430 | ``` 2431 | ### Example (Uncontrolled Component with Ref) 2432 | ```bash 2433 | function UncontrolledInput() { 2434 | const inputRef = React.useRef(); 2435 | 2436 | return ( 2437 |
    2438 | 2439 | 2440 |
    2441 | ); 2442 | } 2443 | ``` 2444 | ## 141) How do you optimize images in React? 2445 | ### Techniques: 2446 | - Use optimized formats like WebP 2447 | - Lazy Loading with React Lazy Load 2448 | - Use a CDN for faster loading 2449 | - Use Image Compression Libraries 2450 | ### Example (Lazy Loading with react-lazy-load-image-component) 2451 | ```bash 2452 | import { LazyLoadImage } from "react-lazy-load-image-component"; 2453 | 2454 | function OptimizedImage() { 2455 | return ; 2456 | } 2457 | ``` 2458 | 2459 | ## 142) How do you implement live chat in a React app? 2460 | ### Using Firebase Firestore 2461 | ```bash 2462 | import { useState, useEffect } from "react"; 2463 | import { db } from "./firebase"; 2464 | import { collection, addDoc, onSnapshot } from "firebase/firestore"; 2465 | 2466 | function ChatApp() { 2467 | const [messages, setMessages] = useState([]); 2468 | const [input, setInput] = useState(""); 2469 | 2470 | useEffect(() => { 2471 | const unsubscribe = onSnapshot(collection(db, "messages"), (snapshot) => { 2472 | setMessages(snapshot.docs.map((doc) => doc.data())); 2473 | }); 2474 | return unsubscribe; 2475 | }, []); 2476 | 2477 | const sendMessage = async () => { 2478 | await addDoc(collection(db, "messages"), { text: input }); 2479 | setInput(""); 2480 | }; 2481 | 2482 | return ( 2483 |
    2484 | {messages.map((msg, index) => ( 2485 |

    {msg.text}

    2486 | ))} 2487 | setInput(e.target.value)} /> 2488 | 2489 |
    2490 | ); 2491 | } 2492 | ``` 2493 | ## 143) What is React PropTypes? 2494 | ### Used for type checking of props in React. 2495 | 2496 | ### Example: 2497 | ```bash 2498 | import PropTypes from "prop-types"; 2499 | 2500 | function Greeting({ name }) { 2501 | return

    Hello, {name}

    ; 2502 | } 2503 | 2504 | Greeting.propTypes = { 2505 | name: PropTypes.string.isRequired, 2506 | }; 2507 | ``` 2508 | ## 144) How do you integrate an API with React? 2509 | ### Example (Using Fetch API) 2510 | ```bash 2511 | function App() { 2512 | const [data, setData] = React.useState([]); 2513 | 2514 | React.useEffect(() => { 2515 | fetch("https://api.example.com/data") 2516 | .then((res) => res.json()) 2517 | .then((data) => setData(data)); 2518 | }, []); 2519 | 2520 | return
      {data.map((item) =>
    • {item.name}
    • )}
    ; 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
    {children}
    ; 2578 | } 2579 | 2580 | Modal.Header = ({ children }) =>

    {children}

    ; 2581 | Modal.Body = ({ children }) =>

    {children}

    ; 2582 | 2583 | function App() { 2584 | return ( 2585 | 2586 | Title 2587 | Body Content 2588 | 2589 | ); 2590 | } 2591 | ``` 2592 | ## 150) How do you design a reusable React component? 2593 | - Use props to make components flexible. 2594 | - Accept children for customization. 2595 | - Avoid hardcoding styles. 2596 | ### Example: 2597 | ```bash 2598 | function Button({ label, onClick }) { 2599 | return ; 2600 | } 2601 | 2681 | 2682 | ); 2683 | } 2684 | ``` 2685 | ## 155) How do you handle asynchronous code in React? 2686 | - You can use async/await inside useEffect or handle Promises. 2687 | 2688 | ### Example: Fetching Data with useEffect 2689 | ```bash 2690 | function FetchData() { 2691 | const [data, setData] = React.useState([]); 2692 | 2693 | React.useEffect(() => { 2694 | async function fetchData() { 2695 | const response = await fetch("https://jsonplaceholder.typicode.com/posts"); 2696 | const result = await response.json(); 2697 | setData(result); 2698 | } 2699 | fetchData(); 2700 | }, []); 2701 | 2702 | return
      {data.map((item) =>
    • {item.title}
    • )}
    ; 2703 | } 2704 | ``` 2705 | 2706 | ## 156) How do you implement internationalization in React? 2707 | - Use libraries like react-intl or i18next. 2708 | 2709 | ### Example using react-i18next 2710 | ```bash 2711 | import { useTranslation } from "react-i18next"; 2712 | 2713 | function App() { 2714 | const { t } = useTranslation(); 2715 | return

    {t("welcome_message")}

    ; 2716 | } 2717 | ``` 2718 | ## 157) How do you debug React Hooks? 2719 | - Use React DevTools to inspect hooks. 2720 | - Use console.log() inside hooks. 2721 | - Avoid infinite loops by setting dependencies correctly in useEffect. 2722 | ## 158) What are WebSockets, and how are they used in React? 2723 | - WebSockets enable real-time communication between the client and server. 2724 | 2725 | ### Example using WebSockets in React 2726 | ```bash 2727 | const socket = new WebSocket("ws://example.com/socket"); 2728 | 2729 | socket.onopen = () => console.log("Connected"); 2730 | socket.onmessage = (event) => console.log("Message:", event.data); 2731 | ``` 2732 | ## 159) How do you implement breadcrumbs in React? 2733 | - Breadcrumbs show the navigation path. 2734 | 2735 | ### Example: Simple Breadcrumb Component 2736 | ```bash 2737 | import { Link } from "react-router-dom"; 2738 | 2739 | function Breadcrumbs({ paths }) { 2740 | return ( 2741 | 2748 | ); 2749 | } 2750 | ``` 2751 | ## 160) How do you implement notifications in React? 2752 | - Use a library like react-toastify. 2753 | 2754 | ### Example: Toast Notifications 2755 | ```bash 2756 | import { ToastContainer, toast } from "react-toastify"; 2757 | import "react-toastify/dist/ReactToastify.css"; 2758 | 2759 | function App() { 2760 | return ( 2761 |
    2762 | 2763 | 2764 |
    2765 | ); 2766 | } 2767 | ``` 2768 | 2769 | ## 161) How do you create a custom hook? 2770 | - Custom hooks allow reusing logic across components. 2771 | 2772 | ### Example: Custom Hook for Fetching Data 2773 | ```bash 2774 | function useFetch(url) { 2775 | const [data, setData] = React.useState(null); 2776 | 2777 | React.useEffect(() => { 2778 | async function fetchData() { 2779 | const response = await fetch(url); 2780 | const result = await response.json(); 2781 | setData(result); 2782 | } 2783 | fetchData(); 2784 | }, [url]); 2785 | 2786 | return data; 2787 | } 2788 | 2789 | function App() { 2790 | const data = useFetch("https://jsonplaceholder.typicode.com/posts"); 2791 | return
    {JSON.stringify(data, null, 2)}
    ; 2792 | } 2793 | ``` 2794 | ## 162) What is the Context API? 2795 | - Used for managing global state without prop drilling. 2796 | 2797 | ### Example: Using Context API for Theme Management 2798 | ```bash 2799 | const ThemeContext = React.createContext(); 2800 | 2801 | function App() { 2802 | const [theme, setTheme] = React.useState("light"); 2803 | 2804 | return ( 2805 | 2806 | 2807 | 2808 | ); 2809 | } 2810 | 2811 | function Child() { 2812 | const { theme } = React.useContext(ThemeContext); 2813 | return

    Current theme: {theme}

    ; 2814 | } 2815 | ``` 2816 | ## 163) How do you integrate Redux with React? 2817 | - Install react-redux and @reduxjs/toolkit. 2818 | - Create a Redux store. 2819 | - Use useSelector to get state and useDispatch to update state. 2820 | ### Example: Redux Setup 2821 | ```bash 2822 | import { configureStore, createSlice } from "@reduxjs/toolkit"; 2823 | import { Provider, useDispatch, useSelector } from "react-redux"; 2824 | 2825 | const counterSlice = createSlice({ 2826 | name: "counter", 2827 | initialState: 0, 2828 | reducers: { 2829 | increment: (state) => state + 1, 2830 | }, 2831 | }); 2832 | 2833 | const store = configureStore({ reducer: counterSlice.reducer }); 2834 | 2835 | function Counter() { 2836 | const count = useSelector((state) => state); 2837 | const dispatch = useDispatch(); 2838 | 2839 | return ; 2840 | } 2841 | 2842 | function App() { 2843 | return ( 2844 | 2845 | 2846 | 2847 | ); 2848 | } 2849 | ``` 2850 | ## 164) How do you handle multiple themes in React? 2851 | ### Example: Using Tailwind CSS Themes 2852 | ```bash 2853 | const themes = { light: "bg-white text-black", dark: "bg-black text-white" }; 2854 | 2855 | function App() { 2856 | const [theme, setTheme] = React.useState("light"); 2857 | 2858 | return ( 2859 |
    2860 | 2861 |
    2862 | ); 2863 | } 2864 | ``` 2865 | ## 165) What is the purpose of React.Children.toArray? 2866 | - It ensures children are a flat array with keys, preventing errors. 2867 | 2868 | ### Example: Using React.Children.toArray 2869 | ```bash 2870 | function Parent({ children }) { 2871 | return
    {React.Children.toArray(children).map((child) => child)}
    ; 2872 | } 2873 | 2874 | function App() { 2875 | return ( 2876 | 2877 |

    Hello

    2878 |

    World

    2879 |
    2880 | ); 2881 | } 2882 | ``` 2883 | ## 166) What are React Design Patterns? 2884 | - React design patterns are best practices and reusable solutions for common problems in React applications. 2885 | 2886 | ### Common Design Patterns in React 2887 | - Container-Presentational Pattern → Separates logic (Container) from UI (Presentational). 2888 | - Higher-Order Components (HOC) → Reusable component logic via function wrappers. 2889 | - Render Props → Uses a function prop to render dynamic UI. 2890 | - Compound Components → Components work together by sharing state/context. 2891 | - Controlled & Uncontrolled Components → Manage form inputs effectively. 2892 | ### Example: Container-Presentational Pattern 2893 | ```bash 2894 | function DataContainer() { 2895 | const [data, setData] = React.useState([]); 2896 | 2897 | React.useEffect(() => { 2898 | fetch("https://jsonplaceholder.typicode.com/posts") 2899 | .then((res) => res.json()) 2900 | .then(setData); 2901 | }, []); 2902 | 2903 | return ; 2904 | } 2905 | 2906 | function PresentationalComponent({ data }) { 2907 | return
      {data.map((item) =>
    • {item.title}
    • )}
    ; 2908 | } 2909 | ``` 2910 | ## 167) How do you implement modals in React? 2911 | - You can use state and conditional rendering or libraries like react-modal. 2912 | 2913 | ### Example: Simple Modal 2914 | ```bash 2915 | function ModalExample() { 2916 | const [isOpen, setIsOpen] = React.useState(false); 2917 | 2918 | return ( 2919 |
    2920 | 2921 | {isOpen && ( 2922 |
    2923 |

    Modal Content

    2924 | 2925 |
    2926 | )} 2927 |
    2928 | ); 2929 | } 2930 | ``` 2931 | ## 168) How do you manage forms in React? 2932 | - Forms can be managed using controlled components, useState(), or libraries like react-hook-form. 2933 | 2934 | ### Example: Controlled Form with useState 2935 | ```bash 2936 | function FormExample() { 2937 | const [name, setName] = React.useState(""); 2938 | 2939 | return ( 2940 |
    e.preventDefault()}> 2941 | setName(e.target.value)} /> 2942 | 2943 |
    2944 | ); 2945 | } 2946 | ``` 2947 | ## 169) What are Render Props in React? 2948 | - A Render Prop is a function prop that determines what gets rendered. 2949 | 2950 | ### Example: Render Props 2951 | ```bash 2952 | function DataProvider({ render }) { 2953 | const [count, setCount] = React.useState(0); 2954 | 2955 | return
    {render(count, () => setCount(count + 1))}
    ; 2956 | } 2957 | 2958 | function App() { 2959 | return ( 2960 | ( 2962 | <> 2963 |

    Count: {count}

    2964 | 2965 | 2966 | )} 2967 | /> 2968 | ); 2969 | } 2970 | ``` 2971 | ## 170) How do you implement lazy loading in React? 2972 | - Use React.lazy() and Suspense to load components on demand. 2973 | 2974 | ### Example: Lazy Loading a Component 2975 | ```bash 2976 | const LazyComponent = React.lazy(() => import("./HeavyComponent")); 2977 | 2978 | function App() { 2979 | return ( 2980 | Loading...}> 2981 | 2982 | 2983 | ); 2984 | } 2985 | ``` 2986 | ## 171) How do you handle forms in React? 2987 | ### Forms can be handled via: 2988 | 2989 | - Controlled components (useState). 2990 | 2991 | - Formik (validations, form state management). 2992 | 2993 | - react-hook-form (efficient form handling). 2994 | 2995 | #### Example: Using react-hook-form 2996 | ```bash 2997 | import { useForm } from "react-hook-form"; 2998 | 2999 | function FormExample() { 3000 | const { register, handleSubmit } = useForm(); 3001 | 3002 | const onSubmit = (data) => console.log(data); 3003 | 3004 | return ( 3005 |
    3006 | 3007 | 3008 |
    3009 | ); 3010 | } 3011 | ``` 3012 | ## 172) How do you manage dependencies in React apps? 3013 | - Use package managers (npm or yarn) to install/update dependencies. 3014 | 3015 | - Use package.json to define exact versions (dependencies and devDependencies). 3016 | 3017 | - Use npm audit to check for vulnerabilities. 3018 | 3019 | - Lock versions (package-lock.json or yarn.lock). 3020 | 3021 | ## 173) How do you debug Redux applications? 3022 | - Use Redux DevTools Extension – Inspect actions, state, and time-travel debugging. 3023 | 3024 | - Log actions in Middleware – Add logging middleware. 3025 | 3026 | - Check mapStateToProps and useSelector for correct state retrieval. 3027 | 3028 | - Use breakpoints in Redux reducers. 3029 | 3030 | #### Example: Logging Redux Actions 3031 | ```bash 3032 | const loggerMiddleware = (store) => (next) => (action) => { 3033 | console.log("Dispatching:", action); 3034 | return next(action); 3035 | }; 3036 | ``` 3037 | ## 174) What is the purpose of useLayoutEffect hook? 3038 | - Similar to useEffect, but runs before the browser paints the screen. 3039 | 3040 | - Used when DOM measurements or synchronous updates are required. 3041 | 3042 | #### Example: Using useLayoutEffect 3043 | ```bash 3044 | function Example() { 3045 | const inputRef = React.useRef(); 3046 | 3047 | React.useLayoutEffect(() => { 3048 | inputRef.current.focus(); 3049 | }, []); 3050 | 3051 | return ; 3052 | } 3053 | ``` 3054 | - Here, useLayoutEffect ensures the input is focused before the browser paints the UI. 3055 | 3056 | ## 175) How do you implement virtual scrolling in React? 3057 | - Virtual scrolling renders only visible elements, improving performance for large lists. 3058 | - Use libraries like react-window or react-virtualized. 3059 | 3060 | #### Example: Virtual Scrolling with react-window 3061 | ```bash 3062 | import { FixedSizeList as List } from "react-window"; 3063 | 3064 | const items = Array.from({ length: 1000 }, (_, i) => `Item ${i}`); 3065 | 3066 | function VirtualizedList() { 3067 | return ( 3068 | 3069 | {({ index, style }) =>
    {items[index]}
    } 3070 |
    3071 | ); 3072 | } 3073 | ``` 3074 | - This only renders visible items instead of all 1000 items. 3075 | 3076 | ## 176) How do you optimize performance in large-scale React applications? 3077 | - Performance optimization in React involves reducing unnecessary renders, optimizing rendering logic, and improving data fetching efficiency. 3078 | 3079 | ### Key Techniques for Optimization 3080 | #### Use React.memo for Pure Components 3081 | 3082 | - Prevents unnecessary re-renders by memoizing components. 3083 | 3084 | ```bash 3085 | const MemoizedComponent = React.memo(({ data }) => { 3086 | console.log("Rendering..."); 3087 | return
    {data}
    ; 3088 | }); 3089 | 3090 | function App() { 3091 | const [count, setCount] = React.useState(0); 3092 | return ( 3093 |
    3094 | 3095 | 3096 |
    3097 | ); 3098 | } 3099 | ``` 3100 | #### Use useCallback to Memoize Functions 3101 | 3102 | - Ensures the same function reference is passed to child components. 3103 | 3104 | ```bash 3105 | const memoizedFunction = useCallback(() => { 3106 | console.log("Function not recreated"); 3107 | }, []); 3108 | ``` 3109 | #### Use useMemo for Expensive Computations 3110 | 3111 | - Memoizes expensive calculations. 3112 | 3113 | ```bash 3114 | const expensiveValue = useMemo(() => computeExpensiveValue(input), [input]); 3115 | ``` 3116 | #### Use Lazy Loading and Code Splitting 3117 | 3118 | - Load components dynamically only when needed. 3119 | 3120 | ```bash 3121 | const LazyComponent = React.lazy(() => import("./HeavyComponent")); 3122 | ``` 3123 | #### Virtualize Long Lists 3124 | 3125 | - Use react-window for efficient rendering of long lists. 3126 | 3127 | ```bash 3128 | import { FixedSizeList as List } from "react-window"; 3129 | ``` 3130 | #### Optimize Context API Performance 3131 | 3132 | - Avoid unnecessary context re-renders by structuring providers efficiently. 3133 | 3134 | ## 177) What are React Fiber and its advantages over the old reconciliation algorithm? 3135 | - React Fiber is React's reconciliation engine that improves performance, concurrency, and responsiveness. 3136 | 3137 | ### Advantages Over Old Reconciliation 3138 | - Time-Slicing for Non-Blocking Rendering 3139 | 3140 | - Fiber splits rendering into chunks, preventing UI blocking. 3141 | 3142 | - Concurrent Mode Support 3143 | 3144 | - Enables Suspense, React Concurrent Mode, and Transitions. 3145 | 3146 | - Error Handling with Error Boundaries 3147 | 3148 | - Improves error recovery and debugging. 3149 | 3150 | - Improved Animation Performance 3151 | 3152 | - Animations are smoother due to incremental rendering. 3153 | 3154 | ## 178) How does React’s rendering mechanism work internally? 3155 | ### React follows a two-phase rendering process: 3156 | 3157 | - Render Phase (Reconciliation) 3158 | 3159 | - Creates a virtual DOM tree. 3160 | 3161 | - Uses React Fiber to determine minimal changes. 3162 | 3163 | - Commit Phase 3164 | 3165 | - Applies changes to the actual DOM. 3166 | 3167 | ## 179) How does React handle concurrent rendering with Suspense and React Concurrent Mode? 3168 | - Concurrent Mode improves responsiveness by allowing rendering to be interruptible. 3169 | 3170 | #### Example: Using Suspense 3171 | ```bash 3172 | const LazyComponent = React.lazy(() => import("./Component")); 3173 | 3174 | function App() { 3175 | return ( 3176 | Loading...}> 3177 | 3178 | 3179 | ); 3180 | } 3181 | ``` 3182 | ## 180) How do you minimize re-renders in React applications? 3183 | - Use React.memo() for components. 3184 | 3185 | - Use useCallback() for function dependencies. 3186 | 3187 | - Optimize Context API usage. 3188 | 3189 | - Use useReducer() for complex state management. 3190 | 3191 | - Use useMemo() for derived values. 3192 | 3193 | 3194 | 3195 | 3196 | ## 181) How do you handle memory leaks in React applications? 3197 | - Unsubscribe from API calls in useEffect. 3198 | 3199 | - Remove event listeners in cleanup functions. 3200 | 3201 | - Avoid storing large objects in state. 3202 | 3203 | ## 182) What is tree shaking, and how does it improve performance in React? 3204 | - Tree shaking eliminates unused JavaScript code during the bundling process. 3205 | 3206 | #### Example: Removing Unused Code 3207 | ```bash 3208 | // Importing only necessary functions 3209 | import { specificFunction } from "large-library"; 3210 | ``` 3211 | ## 183) What is Code Splitting, and how does it work in React? 3212 | - Code Splitting reduces initial load time by dynamically loading JavaScript. 3213 | 3214 | #### Example with React.lazy 3215 | ```bash 3216 | const LazyComponent = React.lazy(() => import("./Component")); 3217 | ``` 3218 | ## 184) How do you handle expensive calculations efficiently in React? 3219 | - Use useMemo() to memoize computations. 3220 | 3221 | - Move expensive logic to Web Workers. 3222 | 3223 | ## 185) What is a Render Prop, and how does it compare to Higher-Order Components? 3224 | - A Render Prop is a function passed as a prop that renders UI dynamically. 3225 | 3226 | #### Example: Render Prop 3227 | ```bash 3228 | const MouseTracker = ({ render }) => { 3229 | const [position, setPosition] = React.useState({ x: 0, y: 0 }); 3230 | 3231 | return
    {render(position)}
    ; 3232 | }; 3233 | ``` 3234 | ## 186) How do you implement an infinite scrolling feature in React? 3235 | - Use the Intersection Observer API or react-infinite-scroll-component. 3236 | 3237 | #### Example 3238 | ```bash 3239 | const observer = new IntersectionObserver((entries) => { 3240 | if (entries[0].isIntersecting) { 3241 | fetchMoreData(); 3242 | } 3243 | }); 3244 | ``` 3245 | ## 187) Best practices for useMemo and useCallback in React 3246 | - Use useMemo() for expensive calculations. 3247 | 3248 | - Use useCallback() for function dependencies. 3249 | 3250 | ## 188) What is whyDidYouRender, and how can it help optimize performance? 3251 | #### whyDidYouRender is a library that helps detect unnecessary re-renders. 3252 | 3253 | - Installation 3254 | ```bash 3255 | npm install @welldone-software/why-did-you-render 3256 | ``` 3257 | ## 189) How does useReducer differ from useState in managing complex state logic? 3258 | - useState() is for simple state updates. 3259 | 3260 | - useReducer() is for complex state logic. 3261 | 3262 | ### Example: useReducer 3263 | ```bash 3264 | const reducer = (state, action) => { 3265 | switch (action.type) { 3266 | case "INCREMENT": 3267 | return { count: state.count + 1 }; 3268 | default: 3269 | return state; 3270 | } 3271 | }; 3272 | 3273 | const [state, dispatch] = useReducer(reducer, { count: 0 }); 3274 | ``` 3275 | ## 190) Difference between useRef, createRef, and forwardRef 3276 | - useRef() → Persistent references. 3277 | 3278 | - createRef() → New reference on every render. 3279 | 3280 | - forwardRef() → Pass refs to child components. 3281 | 3282 | 3283 | 3284 | 3285 | ## 191) How to persist state across page reloads in React? 3286 | - Use localStorage or sessionStorage. 3287 | 3288 | #### Example 3289 | ```bash 3290 | const [data, setData] = React.useState(() => { 3291 | return JSON.parse(localStorage.getItem("data")) || ""; 3292 | }); 3293 | 3294 | React.useEffect(() => { 3295 | localStorage.setItem("data", JSON.stringify(data)); 3296 | }, [data]); 3297 | ``` 3298 | ## 192) How to handle debouncing and throttling in React? 3299 | - Use lodash for debouncing. 3300 | 3301 | #### Example: Debounce Input 3302 | ```bash 3303 | import { debounce } from "lodash"; 3304 | 3305 | const debouncedSearch = debounce((query) => { 3306 | fetchData(query); 3307 | }, 500); 3308 | ``` 3309 | ## 193) How to implement global state management without Redux? 3310 | - React Context API 3311 | 3312 | - Zustand 3313 | 3314 | - Recoil 3315 | 3316 | - Jotai 3317 | 3318 | ## 194) Differences between Redux Toolkit and traditional Redux 3319 | |Feature |Redux Toolkit| Traditional Redux| 3320 | |----- |----- |----- | 3321 | | Boilerplate| Less| More| 3322 | |Configuration| Easy| Manual| 3323 | |Async Handling |createAsyncThunk |Middleware required| 3324 | 3325 | ## 195) What are selectors in Redux, and how do they improve performance? 3326 | - Selectors memoize data to avoid unnecessary calculations. 3327 | 3328 | #### Example 3329 | ```bash 3330 | import { createSelector } from "reselect"; 3331 | 3332 | const selectUsers = (state) => state.users; 3333 | 3334 | const selectActiveUsers = createSelector([selectUsers], (users) => 3335 | users.filter((user) => user.active) 3336 | ); 3337 | ``` 3338 | 3339 | ## 196) How do you create dynamic forms in React? 3340 | - Dynamic forms allow you to create form fields based on data or user interaction. 3341 | 3342 | #### ✅ Use Case: 3343 | - You want to render form inputs based on an array of objects. 3344 | 3345 | #### 🧠 Example: 3346 | ```bash 3347 | const formFields = [ 3348 | { name: 'username', label: 'Username', type: 'text' }, 3349 | { name: 'email', label: 'Email', type: 'email' }, 3350 | { name: 'age', label: 'Age', type: 'number' } 3351 | ]; 3352 | 3353 | function DynamicForm() { 3354 | const [formData, setFormData] = React.useState({}); 3355 | 3356 | const handleChange = (e) => { 3357 | setFormData({ ...formData, [e.target.name]: e.target.value }); 3358 | }; 3359 | 3360 | const handleSubmit = (e) => { 3361 | e.preventDefault(); 3362 | console.log(formData); 3363 | }; 3364 | 3365 | return ( 3366 |
    3367 | {formFields.map(field => ( 3368 |
    3369 | 3370 | 3376 |
    3377 | ))} 3378 | 3379 |
    3380 | ); 3381 | } 3382 | ``` 3383 | ## 197) How do you handle asynchronous code in React? 3384 | - Asynchronous code (e.g., API calls) is handled using async/await inside useEffect or event handlers. 3385 | 3386 | #### 🧠 Example: Fetching Data 3387 | ```bash 3388 | function UsersList() { 3389 | const [users, setUsers] = React.useState([]); 3390 | const [loading, setLoading] = React.useState(true); 3391 | 3392 | React.useEffect(() => { 3393 | const fetchUsers = async () => { 3394 | const res = await fetch("https://jsonplaceholder.typicode.com/users"); 3395 | const data = await res.json(); 3396 | setUsers(data); 3397 | setLoading(false); 3398 | }; 3399 | fetchUsers(); 3400 | }, []); 3401 | 3402 | if (loading) return

    Loading...

    ; 3403 | 3404 | return ( 3405 |
      3406 | {users.map(user =>
    • {user.name}
    • )} 3407 |
    3408 | ); 3409 | } 3410 | ``` 3411 | ## 198) What is React Transition Group? 3412 | - It’s a library for adding animations/transitions to components as they mount/unmount. 3413 | 3414 | #### 📦 Installation: 3415 | ```bash 3416 | npm install react-transition-group 3417 | ``` 3418 | ### 🧠 Example: 3419 | ```bash 3420 | import { CSSTransition } from 'react-transition-group'; 3421 | import './fade.css'; 3422 | 3423 | function FadeComponent({ show }) { 3424 | return ( 3425 | 3431 |
    Hello with Transition!
    3432 |
    3433 | ); 3434 | } 3435 | ``` 3436 | #### 🔥 CSS (fade.css) 3437 | ```bash 3438 | .fade-enter { 3439 | opacity: 0; 3440 | } 3441 | .fade-enter-active { 3442 | opacity: 1; 3443 | transition: opacity 300ms; 3444 | } 3445 | .fade-exit { 3446 | opacity: 1; 3447 | } 3448 | .fade-exit-active { 3449 | opacity: 0; 3450 | transition: opacity 300ms; 3451 | } 3452 | ``` 3453 | ## 199) How do you implement internationalization (i18n) in React? 3454 | - Use libraries like react-i18next for multi-language support. 3455 | 3456 | #### 📦 Installation: 3457 | ```bash 3458 | npm install react-i18next i18next 3459 | ``` 3460 | #### 🧠 Example: 3461 | ```bash 3462 | import { useTranslation } from 'react-i18next'; 3463 | 3464 | function App() { 3465 | const { t, i18n } = useTranslation(); 3466 | 3467 | return ( 3468 |
    3469 |

    {t('welcome')}

    3470 | 3471 | 3472 |
    3473 | ); 3474 | } 3475 | ``` 3476 | - 🗂 i18n Translation File (en.json) 3477 | ```bash 3478 | { 3479 | "welcome": "Welcome to our app" 3480 | } 3481 | ``` 3482 | 3483 | ## 200) What are WebSockets, and how are they used in React? 3484 | - WebSockets provide real-time communication between client and server. 3485 | 3486 | #### 📦 Example with socket.io-client 3487 | ```bash 3488 | npm install socket.io-client 3489 | ``` 3490 | #### 🧠 Example: 3491 | ```bash 3492 | import { useEffect } from 'react'; 3493 | import io from 'socket.io-client'; 3494 | 3495 | const socket = io("http://localhost:3001"); 3496 | 3497 | function Chat() { 3498 | useEffect(() => { 3499 | socket.on("message", msg => { 3500 | console.log("New message:", msg); 3501 | }); 3502 | 3503 | return () => socket.disconnect(); 3504 | }, []); 3505 | 3506 | const sendMessage = () => { 3507 | socket.emit("message", "Hello from React"); 3508 | }; 3509 | 3510 | return ; 3511 | } 3512 | ``` 3513 | 3514 | ## Thank You ❤️ 3515 | --------------------------------------------------------------------------------