React.js Theory & Practical Questions
1. What is React?
React is an open-source JavaScript library developed by Facebook for building user interfaces, specifically for single-page applications. It allows developers to create large web applications that can change data without reloading the page.
2. What are the main features of React?
- Virtual DOM: Efficiently updates and renders components.\n2. Component-Based: Logic is written in JavaScript instead of templates.\n3. Unidirectional Data Flow: Data flows in one direction, making code predictable.\n4. JSX: A syntax extension that allows writing HTML-like code in JavaScript.
3. What is JSX?
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like code directly within React. It makes the code more readable and easier to write.
4. What is the difference between functional and class components?
- Functional Components: Simple JS functions that accept props and return JSX. They use Hooks (
useState,useEffect) for state and lifecycle management.\n- Class Components: ES6 classes that extendReact.Component. They usethis.stateand lifecycle methods likecomponentDidMount.
5. What are hooks in React?
Hooks are functions that let you "hook into" React state and lifecycle features from functional components. They were introduced in React 16.8 to allow state management without writing classes.
6. Explain the `useState` hook.
The useState hook is used to add state to a functional component. It returns an array with two elements: the current state value and a function to update it.\n\njavascript\nconst [count, setCount] = useState(0);\n
7. Explain the `useEffect` hook.
The useEffect hook allows you to perform side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount.
8. What is the Virtual DOM and how does it work?
The Virtual DOM is a lightweight copy of the real DOM. When the state of an object changes, React first updates the Virtual DOM. Then, it compares the current Virtual DOM with the previous one (Diffing) and updates only the changed parts in the real DOM (Reconciliation).
9. What is the difference between Props and State?
- Props: Immutable data passed from a parent component to a child component. They are read-only.\n- State: Mutable data managed within the component itself. Changes to state trigger a re-render.
10. What is "Prop Drilling" and how can you avoid it?
Prop Drilling is the process of passing data through multiple levels of nested components that do not need the data themselves. It can be avoided using the Context API, Redux, or Component Composition.
11. Explain the `useContext` hook.
The useContext hook allows you to subscribe to React context without nesting. It provides a way to share data (like themes or user info) globally across the component tree without prop drilling.
12. What is the purpose of the `key` prop in lists?
Keys help React identify which items in a list have changed, been added, or been removed. They provide a stable identity to elements, which optimizes the rendering performance during the reconciliation process.
13. How do you handle forms in React?
Forms can be handled using Controlled Components, where the form data is handled by the component state, or Uncontrolled Components, where the form data is handled by the DOM itself (using refs).
14. What is the difference between controlled and uncontrolled components?
- Controlled: The component state is the "single source of truth" for form inputs.\n- Uncontrolled: The DOM maintains the form state, and you access values using
useRef.
15. Explain Higher-Order Components (HOC).
An HOC is a function that takes a component and returns a new component with additional props or logic. It is a pattern used for reusing component logic (e.g., authentication, logging).
16. What are Render Props?
Render Props is a technique for sharing code between React components using a prop whose value is a function. The component calls this function to determine what to render.
17. Explain `useMemo` and `useCallback`.
useMemo: Memoizes the result of a calculation to avoid expensive re-computations on every render.\n-useCallback: Memoizes a function definition to prevent it from being recreated on every render, which is useful when passing functions to memoized child components.
18. What is `React.memo`?
React.memo is a higher-order component that memoizes a functional component. It prevents the component from re-rendering if its props have not changed.
19. What are Error Boundaries?
Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the whole app. They must be implemented as class components.
20. What are Portals in React?
Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component. This is commonly used for modals, tooltips, and floating menus.
21. Explain the component lifecycle in class components.
- Mounting:
constructor,render,componentDidMount.\n2. Updating:shouldComponentUpdate,render,componentDidUpdate.\n3. Unmounting:componentWillUnmount.
22. How to optimize performance in a React application?
Optimization techniques include:\n- Using React.memo, useMemo, and useCallback.\n- Code splitting with React.lazy and Suspense.\n- Virtualizing long lists (e.g., react-window).\n- Avoiding unnecessary state updates.
23. What is the difference between `Shadow DOM` and `Virtual DOM`?
- Shadow DOM: A browser technology used for scoping variables and CSS in Web Components.\n- Virtual DOM: A library-level (React) concept used to optimize rendering performance by minimizing real DOM updates.
24. Explain the `useRef` hook.
The useRef hook returns a mutable ref object whose .current property is initialized with the passed argument. It is used to access DOM elements directly or to store mutable values that don’t trigger a re-render.
25. What is "Forwarding Refs"?
Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is useful for highly reusable components like buttons or inputs.
26. What are custom hooks?
Custom hooks are JavaScript functions whose names start with "use" and that may call other hooks. They allow you to extract component logic into reusable functions.
27. Explain the `useReducer` hook.
The useReducer hook is an alternative to useState for managing complex state logic. It takes a reducer function and an initial state, returning the current state and a dispatch function.
28. Difference between `useReducer` and `useState`.
useState: Best for simple state values (strings, booleans, numbers).\n-useReducer: Better for complex state objects or when the next state depends on the previous one.
29. What is React Router?
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
30. Explain Lazy Loading in React.
Lazy loading is a technique to defer the loading of non-critical resources at page load time. In React, this is achieved using React.lazy() to import components only when they are needed.
31. What is the purpose of `Suspense`?
Suspense is a component that lets you "wait" for some code to load and declaratively specify a loading state (like a spinner) while we’re waiting.
32. How to fetch data in React?
Data can be fetched using the native fetch API or libraries like Axios inside the useEffect hook, or using modern libraries like React Query and SWR for better caching and synchronization.
33. What is Redux?
Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.
34. Explain the core principles of Redux.
- Single Source of Truth: The entire state of the app is stored in an object tree within a single store.\n2. State is Read-Only: The only way to change the state is to emit an action.\n3. Changes are made with Pure Functions: To specify how the state tree is transformed by actions, you write pure reducers.
35. What is `redux-thunk`?
redux-thunk is a middleware for Redux that allows you to write action creators that return a function instead of an action. This is used to handle asynchronous logic like API calls.
36. Difference between Redux and Context API.
- Context API: Built-in to React, great for low-frequency updates (e.g., theme, locale).\n- Redux: External library, better for high-frequency updates, complex state logic, and offers powerful debugging tools (Redux DevTools).
37. What is `useLayoutEffect`?
It is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render to avoid visual flickers.
38. Explain Strict Mode in React.
Strict Mode is a tool for highlighting potential problems in an application. It activates additional checks and warnings for its descendants, such as identifying unsafe lifecycles or legacy API usage.
39. What are Fragments?
Fragments (<React.Fragment> or <>) let you group a list of children without adding extra nodes to the DOM.
40. How to handle errors in functional components?
While Error Boundaries (class components) are needed to catch rendering errors, local errors in functional components are handled using try...catch blocks inside effects or event handlers.
41. What is `hydration` in Next.js/React?
Hydration is the process of mapping the event listeners and React logic to the static HTML that was sent from the server, making the page interactive.
42. Difference between `SSR` and `CSR`.
- SSR (Server-Side Rendering): HTML is generated on the server for each request. Better for SEO and initial load speed.\n- CSR (Client-Side Rendering): The browser downloads a minimal HTML file and renders the content using JavaScript.
43. What is `Static Site Generation (SSG)`?
SSG generates HTML at build time. The pre-rendered HTML is then reused on each request. It is the fastest rendering method for content that doesn’t change often.
44. Explain `Incremental Static Regeneration (ISR)`.
ISR allows you to update static pages after you’ve built your site, without needing to rebuild the entire site. You can re-generate specific pages in the background as traffic comes in.
45. What is the `children` prop?
children is a special prop that allows you to pass components or elements as data to other components, enabling powerful composition patterns.
46. How to "lift state up"?
"Lifting state up" involves moving the state to the closest common ancestor of the components that need it, and then passing it down via props. This ensures a "single source of truth".
47. What is the difference between `element` and `component`?
- Element: A plain object describing what you want to see on the screen (e.g.,
const el = <h1>Hello</h1>).\n- Component: A function or class that accepts props and returns a React element.
48. What is a `synthetic event` in React?
A synthetic event is a cross-browser wrapper around the browser’s native event. It has the same interface as the native event but works identically across all browsers.
49. How to use CSS in React?
CSS can be applied via:\n- Inline Styles: style={{ color: "red" }}\n- External Stylesheets: import "./App.css"\n- CSS Modules: import styles from "./App.module.css"\n- CSS-in-JS: Styled Components or Emotion.
50. What are `CSS Modules`?
CSS Modules allow you to write CSS that is scoped locally to a specific component by automatically generating unique class names, preventing style conflicts.
51. Explain `Styled Components`.
Styled Components is a library for React that uses tagged template literals to style your components. It allows you to write actual CSS code to style your components without worrying about class name collisions.
52. How to test React components?
React components are typically tested using Jest (test runner) and React Testing Library (focuses on testing components from the user's perspective) or Enzyme (focuses on implementation details).