DEV Community

Softden 2005
Softden 2005

Posted on

πŸ“š Comprehensive Guide to React

React Fundamentals

  1. What is React? πŸ€”

    • Explanation: React is an open-source JavaScript library for building user interfaces, particularly for single-page applications. It allows developers to create reusable UI components.
    • Use Case: Used to develop dynamic web applications where data changes frequently, such as dashboards.
  2. What are the main features of React? 🌟

    • Explanation:
      • Component-Based Architecture: Reusable UI components.
      • JSX: A syntax extension that allows mixing HTML with JavaScript.
      • Virtual DOM: Efficient updates to the UI by minimizing direct DOM manipulations.
      • One-Way Data Binding: Ensures data flows in one direction for easier debugging.
    • Use Case: Building scalable applications with a clear structure.
  3. What is JSX? πŸ“œ

    • Explanation: JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML elements in JavaScript. It simplifies the creation of React components.
    • Example:
     const element = <h1>Hello, World!</h1>;
    
  • Use Case: Makes the code more readable and easier to write when creating UI components.
  1. Explain the concept of components in React. 🧩

    • Explanation: Components are independent, reusable pieces of UI. They can be functional or class-based and can accept inputs (props).
    • Example:
     function Greeting(props) {
       return <h1>Hello, {props.name}!</h1>;
     }
    
  • Use Case: Breaking down complex UIs into smaller, manageable parts.
  1. What is the difference between a class component and a functional component? βš–οΈ

    • Explanation:
      • Class Components: Extend from React.Component, can have lifecycle methods, and manage state.
      • Functional Components: Simpler, used for stateless components, but with hooks, they can manage state and lifecycle.
    • Example:
     // Class Component
     class MyComponent extends React.Component {
       render() {
         return <div>Hello, Class!</div>;
       }
     }
    
     // Functional Component
     function MyComponent() {
       return <div>Hello, Functional!</div>;
     }
    
  • Use Case: Use functional components for simpler, stateless parts of the UI, class components for more complex behavior.
  1. What are props in React? πŸ“¦

    • Explanation: Props (short for properties) are read-only attributes passed from a parent component to a child component. They allow data to flow within the component hierarchy.
    • Example:
     function Greeting(props) {
       return <h1>Hello, {props.name}!</h1>;
     }
    
  • Use Case: Passing data to components to create dynamic UIs.
  1. How do you manage state in React? πŸ—„οΈ

    • Explanation: State can be managed using the useState hook in functional components or through this.state in class components. It allows components to keep track of data that changes over time.
    • Example:
     // Functional Component
     const [count, setCount] = useState(0);
    
  • Use Case: Managing form inputs, toggles, and any UI element that changes based on user interaction.
  1. What is the difference between State and Props in React? πŸ”

    • Explanation:
      • State: Managed within the component, mutable, and determines the component’s behavior and rendering.
      • Props: Passed to components, immutable, and used to communicate between components.
    • Use Case: Use state for internal data management, props for passing data and behavior to child components.
  2. What is the Virtual DOM in React? πŸ–₯️

    • Explanation: The Virtual DOM is a lightweight copy of the actual DOM. React updates this virtual representation first, compares it with the real DOM, and only updates the changed parts for performance optimization.
    • Use Case: Enhancing performance in applications where frequent updates occur, reducing the number of direct DOM manipulations.

Lifecycle & Hooks

  1. What are lifecycle methods in React? ⏳

    • Explanation: Lifecycle methods are hooks in class components that allow you to run code at specific points in a component’s life cycle (mounting, updating, and unmounting).
    • Example:
      • componentDidMount()
      • componentDidUpdate()
      • componentWillUnmount()
    • Use Case: Performing side effects such as API calls after a component mounts.
  2. What is the difference between ComponentDidMount, ComponentDidUpdate, and ComponentWillUnmount in class components? πŸ•°οΈ

    • Explanation:
      • componentDidMount: Invoked immediately after a component is mounted. Ideal for fetching data.
      • componentDidUpdate: Invoked immediately after updating occurs. Suitable for operations based on prop changes.
      • componentWillUnmount: Invoked immediately before a component is unmounted. Useful for cleanup (e.g., canceling API requests).
    • Use Case: Managing resources effectively and preventing memory leaks.
  3. What is the useEffect Hook and how is it different from useLayoutEffect? ⏲️

    • Explanation:
      • useEffect: A hook that runs side effects after rendering, ideal for data fetching, subscriptions, or manually changing the DOM.
      • useLayoutEffect: Similar, but it runs synchronously after all DOM mutations. Useful for measuring the layout.
    • Example:
      useEffect(() => {
        // side effect code
      }, [dependencies]);
    
- **Use Case:** Managing side effects in functional components without blocking the browser's painting.
Enter fullscreen mode Exit fullscreen mode
  1. What is the useState Hook and how do you use it? πŸŽ›οΈ

    • Explanation: useState is a hook that lets you add state to functional components. It returns a state variable and a function to update it.
    • Example:
      const [count, setCount] = useState(0);
    
- **Use Case:** Managing local component state like user input or toggles.
Enter fullscreen mode Exit fullscreen mode
  1. What is the useCallback Hook and when would you use it? πŸ”„

    • Explanation: useCallback returns a memoized callback function that only changes if one of the dependencies has changed. It helps prevent unnecessary re-renders.
    • Example:
      const memoizedCallback = useCallback(() => {
        doSomething(a, b);
      }, [a, b]);
    
- **Use Case:** Passing callbacks to optimized child components that rely on reference equality to prevent re-renders.
Enter fullscreen mode Exit fullscreen mode
  1. What is the difference between useMemo and useCallback? 🧠 vs πŸ”„

    • Explanation:
      • useMemo: Memoizes the result of a computation.
      • useCallback: Memoizes the function itself.
    • Example:
      const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
    
- **Use Case:** Use `useMemo` for expensive calculations, and `useCallback` for functions passed as props.
Enter fullscreen mode Exit fullscreen mode
  1. What is useReducer Hook and when should you use it? πŸ“‰

    • Explanation: useReducer is a hook for managing more complex state logic in a functional component, often used when the state depends on previous states.
    • Example:
      const [state, dispatch] = useReducer(reducer, initialState);
    
- **Use Case:** Handling state in larger components where multiple state variables are related.
Enter fullscreen mode Exit fullscreen mode
  1. What is the useRef Hook and how is it used? πŸ“

    • Explanation: useRef returns a mutable ref object whose .current property is initialized to the passed argument. It can hold a reference to a DOM element or a mutable value.
    • Example:
      const inputRef = useRef(null);
      const focusInput = () => {
        inputRef.current.focus();
      };
    
- **Use Case:** Accessing DOM elements directly for input focus, animations, or integrating with third-party libraries.
Enter fullscreen mode Exit fullscreen mode
  1. What is the purpose of the useContext Hook? 🌐

    • Explanation: useContext allows you to consume context directly in functional components without needing to wrap them in a Context.Consumer.
    • Example:
      const value = useContext(MyContext);
    
- **Use Case:** Simplifying the consumption of context for global state management.
Enter fullscreen mode Exit fullscreen mode
  1. How do you create a custom hook? πŸ”§

    • Explanation: A custom hook is a JavaScript function that starts with "use" and can call other hooks. It can encapsulate logic that needs to be reused across components.
    • Example:
      function useFetch(url) {
        const [data, setData] = useState(null);
        useEffect(() => {
          fetch(url).then(response => response.json()).then(setData);
        }, [url]);
        return data;
      }
    
- **
Enter fullscreen mode Exit fullscreen mode

Use Case:** Reusing stateful logic, like fetching data or form handling.

  1. What is React.memo and how is it different from useMemo? πŸ“

    • Explanation: React.memo is a higher-order component that memoizes a component, preventing unnecessary re-renders. useMemo is used to memoize values within a component.
    • Example:
      const MemoizedComponent = React.memo(MyComponent);
    
- **Use Case:** Optimizing functional components that render the same output given the same props.
Enter fullscreen mode Exit fullscreen mode

State Management & Context

  1. How does React handle state management? What are some libraries for managing state in larger applications? πŸ“¦

    • Explanation: React provides built-in state management through useState and useReducer. For larger applications, libraries like Redux, MobX, and Recoil can be used to manage global state.
    • Use Case: Using Redux for a complex application to manage the global state across multiple components.
  2. What is the Context API in React and how do you create a Context? 🌐

    • Explanation: The Context API allows you to share values (like state) between components without prop drilling. It is created using React.createContext().
    • Example:
      const MyContext = React.createContext();
    
- **Use Case:** Sharing theme settings or user authentication status across components.
Enter fullscreen mode Exit fullscreen mode
  1. What is Prop Drilling and how can it be avoided? πŸ”„

    • Explanation: Prop drilling is the process of passing data through many layers of components. It can be avoided using the Context API or state management libraries.
    • Use Case: Using Context API to eliminate the need to pass props through every component.
  2. What are Higher-Order Components (HOCs)? πŸ—οΈ

    • Explanation: HOCs are functions that take a component and return a new component. They are used to share common functionality across multiple components.
    • Example:
      const withExtraInfo = (WrappedComponent) => {
        return (props) => {
          return <WrappedComponent {...props} extraInfo="Extra Data" />;
        };
      };
    
- **Use Case:** Adding logging, data fetching, or theming to components without modifying their structure.
Enter fullscreen mode Exit fullscreen mode
  1. What are Controlled and Uncontrolled Components in React? πŸŽ›οΈ

    • Explanation:
      • Controlled Components: The component’s state is controlled by React. The input value is managed through the component state.
      • Uncontrolled Components: The input maintains its own internal state. React does not control the input value.
    • Example:
      // Controlled
      <input type="text" value={value} onChange={e => setValue(e.target.value)} />
    
      // Uncontrolled
      <input type="text" ref={inputRef} />
    
- **Use Case:** Controlled components for forms, uncontrolled for simple input scenarios.
Enter fullscreen mode Exit fullscreen mode
  1. What is a ForwardRef in React? πŸ”—

    • Explanation: ForwardRef is a React API that allows a parent component to pass a ref through a component to one of its children.
    • Example:
      const FancyInput = React.forwardRef((props, ref) => (
        <input ref={ref} className="fancy-input" />
      ));
    
- **Use Case:** Allowing parent components to access the ref of child components for DOM manipulations.
Enter fullscreen mode Exit fullscreen mode

Performance Optimization

  1. How do you optimize performance in a React app? πŸš€

    • Explanation:
      • Use memoization (React.memo, useMemo, useCallback).
      • Code splitting and lazy loading with React.lazy.
      • Optimize rendering using the Virtual DOM.
      • Avoid inline functions and anonymous functions in render.
    • Use Case: Ensuring a smooth user experience in applications with frequent updates or large datasets.
  2. What is React.lazy and how do you use it? 😴

    • Explanation: React.lazy allows you to dynamically import components as they are needed, enabling code splitting.
    • Example:
      const OtherComponent = React.lazy(() => import('./OtherComponent'));
    
- **Use Case:** Reducing the initial load time by loading components only when they are required.
Enter fullscreen mode Exit fullscreen mode
  1. What is Code Splitting in React? πŸ“¦

    • Explanation: Code splitting is the practice of breaking your code into smaller chunks which can be loaded on demand. This improves loading times and reduces the initial bundle size.
    • Use Case: Loading routes only when the user navigates to them.
  2. What are some performance optimization techniques in SSR? πŸ–₯️

    • Explanation:
      • Minimize server-side rendering time by optimizing data fetching.
      • Use caching strategies to store server-rendered pages.
      • Implement code splitting on the server.
    • Use Case: Improving the speed and efficiency of server-rendered applications.
  3. How do you handle large lists in React? πŸ“œ

    • Explanation: Use techniques like windowing or virtualization with libraries such as react-window or react-virtualized to only render what is visible on the screen.
    • Use Case: Efficiently rendering long lists (e.g., thousands of items) without performance issues.

Advanced Concepts

  1. What is Server-Side Rendering (SSR) in React? 🌐

    • Explanation: SSR is the process of rendering web pages on the server instead of in the browser. It improves performance and SEO by delivering fully rendered pages.
    • Use Case: Websites that require fast loading and SEO optimization.
  2. What is Client-Side Rendering (CSR) in React? πŸ’»

    • Explanation: CSR means that the web page is rendered in the browser, allowing for a dynamic, interactive user experience. The initial load might be slower compared to SSR.
    • Use Case: Single-page applications where user interaction is crucial.
  3. How is SSR implemented in React using Next.js? βš™οΈ

    • Explanation: Next.js simplifies the process of SSR in React by providing built-in functions for data fetching (getServerSideProps) that run on the server.
    • Example:
      export async function getServerSideProps() {
        const res = await fetch('https://api.example.com/data');
        const data = await res.json();
        return { props: { data } };
      }
    
- **Use Case:** Building SEO-friendly React applications with fast loading times.
Enter fullscreen mode Exit fullscreen mode
  1. What is the Hydration Process in SSR? πŸ’§

    • Explanation: Hydration is the process of attaching event listeners to the server-rendered HTML when it is loaded in the browser, turning it into a fully interactive React application.
    • Use Case: Ensuring the React app is interactive without requiring a complete re-render.
  2. What is Static Site Generation (SSG), and how does it differ from SSR and CSR? πŸ—οΈ

    • Explanation: SSG generates HTML at build time, serving static pages. Unlike SSR (runtime rendering) and CSR (client-side rendering), SSG is faster but less dynamic.
    • Use Case: Blogs or documentation sites where content does not change often.
  3. What is Incremental Static Regeneration (ISR)? πŸ”„

    • Explanation: ISR allows you to update static pages incrementally without needing to rebuild the entire site. You can define a revalidation period to refresh content.
    • Use Case: E-commerce sites where products change frequently but static generation is still desirable.
  4. How do you combine CSR and SSR in a React app? πŸ”—

    • Explanation: You can leverage frameworks like Next.js to implement both CSR and SSR in your application. Use SSR for initial page loads and CSR for subsequent navigation.
    • Use Case: Hybrid applications that need both fast initial loading and interactivity.
  5. What is React Hydration Error, and how can you avoid it? 🚨

    • Explanation: Hydration errors occur when the server-rendered markup does not match the client-side rendered markup. This can lead to UI inconsistencies.
    • Solution: Ensure that the server and client render the same output by avoiding state-based rendering in the initial render.
    • Use Case: Maintaining consistency between SSR and CSR rendered components.

React Router & Navigation

  1. How does React Router work? πŸ›€οΈ

    • Explanation: React Router is a library that enables dynamic routing in React applications. It uses the browser's history API to keep UI in sync with the URL.
    • Use Case: Creating multi-page applications with navigation between different components without full page reloads.
  2. How do you set up a basic router in React Router? βš™οΈ

    • Explanation: Import BrowserRouter and Route from react-router-dom, then define routes within the BrowserRouter.
    • Example:
      import { BrowserRouter as Router, Route } from 'react-router-dom';
      function App() {
        return (
          <Router>
            <Route path="/" component={Home} />
            <Route path="/about" component={About} />
          </Router>
        );
      }
    
- **Use Case:** Navigating between components based on the URL path.
Enter fullscreen mode Exit fullscreen mode
  1. What are nested routes in React Router? 🌐 -

Explanation: Nested routes allow you to define child routes within parent routes, enabling complex routing structures.
- Example:

  ```jsx
  <Route path="/dashboard">
    <Dashboard>
      <Route path="analytics" component={Analytics} />
      <Route path="settings" component={Settings} />
    </Dashboard>
  </Route>
  ```
Enter fullscreen mode Exit fullscreen mode
- **Use Case:** Organizing routing for a dashboard with multiple sections.
Enter fullscreen mode Exit fullscreen mode
  1. What is the purpose of the useHistory Hook in React Router? πŸ“œ

    • Explanation: The useHistory hook gives access to the history instance used by React Router, allowing navigation programmatically.
    • Example:
      const history = useHistory();
      const handleClick = () => {
        history.push('/home');
      };
    
- **Use Case:** Redirecting users after form submissions or other actions.
Enter fullscreen mode Exit fullscreen mode

Error Handling & Testing

  1. How do you handle errors in React components? πŸ› οΈ

    • Explanation: Use error boundaries to catch JavaScript errors in the component tree and display a fallback UI. Implement try-catch blocks in async functions.
    • Example:
      class ErrorBoundary extends React.Component {
        constructor(props) {
          super(props);
          this.state = { hasError: false };
        }
    
        static getDerivedStateFromError(error) {
          return { hasError: true };
        }
    
        componentDidCatch(error, errorInfo) {
          // Log error to an error reporting service
        }
    
        render() {
          if (this.state.hasError) {
            return <h1>Something went wrong.</h1>;
          }
          return this.props.children;
        }
      }
    
- **Use Case:** Preventing app crashes by displaying user-friendly error messages.
Enter fullscreen mode Exit fullscreen mode
  1. What is React’s Strict Mode and why do we use it? 🚨

    • Explanation: Strict Mode is a development tool that helps to identify potential problems in an application by highlighting unsafe lifecycle methods, legacy API usage, and more.
    • Use Case: Improving the quality of code by enforcing best practices during development.
  2. How do you test a React component? πŸ”

    • Explanation: You can test React components using libraries like Jest and React Testing Library. You can write unit tests to check rendering, events, and UI changes.
    • Example:
      test('renders learn react link', () => {
        render(<App />);
        const linkElement = screen.getByText(/learn react/i);
        expect(linkElement).toBeInTheDocument();
      });
    
- **Use Case:** Ensuring components behave as expected under different scenarios.
Enter fullscreen mode Exit fullscreen mode
  1. What is shallow rendering in testing? πŸ”¬

    • Explanation: Shallow rendering is a testing technique where you render a component without its child components, allowing you to isolate and test the component in isolation.
    • Use Case: Testing component logic without worrying about child components.
  2. What is the purpose of the React Testing Library? πŸ“š

    • Explanation: React Testing Library focuses on testing components from the user's perspective, encouraging best practices in testing by using real DOM interactions.
    • Use Case: Writing tests that closely resemble user interactions to ensure functionality works as expected.

Miscellaneous

  1. What are React Fragments and why do we use them? 🧩

    • Explanation: React Fragments allow you to group multiple children without adding extra nodes to the DOM. They can be declared with <Fragment> or <> shorthand.
    • Example:
      return (
        <Fragment>
          <ChildA />
          <ChildB />
        </Fragment>
      );
    
- **Use Case:** Returning multiple elements from a component without wrapping them in a div.
Enter fullscreen mode Exit fullscreen mode
  1. What are Render Props in React? 🎭

    • Explanation: Render Props is a technique for sharing code between React components using a prop whose value is a function.
    • Example:
      const DataProvider = ({ render }) => {
        const data = fetchData();
        return render(data);
      };
    
      <DataProvider render={data => <DisplayData data={data} />} />;
    
- **Use Case:** Sharing data-fetching logic between multiple components.
Enter fullscreen mode Exit fullscreen mode
  1. What is the purpose of the key prop in React? πŸ”‘

    • Explanation: The key prop is a special string attribute that helps React identify which items have changed, are added, or are removed, optimizing rendering.
    • Example:
      {items.map(item => (
        <ListItem key={item.id} item={item} />
      ))}
    
- **Use Case:** Maintaining the state of list items when the list changes.
Enter fullscreen mode Exit fullscreen mode
  1. What is the difference between Synthetic Events and normal events in React? ⚑

    • Explanation: Synthetic events are a cross-browser wrapper around the browser's native events, ensuring consistent behavior across different browsers. They are normalized and pooled by React for performance.
    • Use Case: Ensuring consistent event handling in a React application.
  2. What is the significance of the className attribute in React? 🎨

    • Explanation: The className attribute is used in React instead of the standard class attribute to apply CSS classes to elements, as class is a reserved keyword in JavaScript.
    • Example:
      <div className="my-class">Content</div>
    
- **Use Case:** Styling React components with CSS.
Enter fullscreen mode Exit fullscreen mode
  1. How do you style React components? 🎨

    • Explanation: You can style React components using CSS stylesheets, inline styles, CSS modules, or libraries like styled-components.
    • Example:
      const style = { color: 'blue' };
      <div style={style}>Styled Text</div>
    
- **Use Case:** Applying styles to components dynamically.
Enter fullscreen mode Exit fullscreen mode
  1. What are CSS Modules and styled-components in React? πŸ“

    • Explanation:
      • CSS Modules: Allow you to write CSS that is scoped to a single component, avoiding global scope issues.
      • Styled-components: A library for styling components using tagged template literals, enabling dynamic styling based on props.
    • Use Case: Organizing and managing styles effectively in large applications.
  2. How do you handle form submission and validation in React? πŸ“‘

    • Explanation: Use controlled components to manage form state. Implement validation using libraries like Formik or validate fields on input changes.
    • Example:
      const handleSubmit = (e) => {
        e.preventDefault();
        // Validation logic
      };
    
      <form onSubmit={handleSubmit}>
        <input type="text" value={value} onChange={handleChange} />
        <button type="submit">Submit</button>
      </form>
    
- **Use Case:** Ensuring user input is correctly handled and validated before submission.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)