Skip to content

Latest commit

 

History

History
262 lines (195 loc) · 7.94 KB

12.React_Others.md

File metadata and controls

262 lines (195 loc) · 7.94 KB

100 React Questions (Others)

Q1. What is a Higher-Order Component in React? V. IMP.

A Higher-Order component is a component which takes another component as a arguement and adds extra features to another component.

HOC can be used for providing logging functionality to all the components in a reusable way.

HocLogger.js:

//High Order Component
const HocLogger = (HocUse) => {
  return function WithLogger(props) {
    console.log("I am from logger");
    return <HocUse />;
  };
};
export default HocLogger;

// HocUse.js: Normal Component will HOC
const HocUse = () => {
  return <div>My Component Content</div>;
};

export default Hoc(HocUse);

index.js

root.render(<HocUse></HocUse>);

Q2. What are the 5 ways to Style React components? Explain Inline Styles?

5 ways to Style React components

  • Inline Styles

  • CSS Stylesheets

  • CSS-Modules

  • Global Stylesheets

  • CSS Frameworks

inline styles

import React from "react";

const AppInlineStyle = () => {
    return (
        <div>
            <h1 style={inlineStyles.title}>Inline</h1>
        </div>
    );
};

const inlineStyles = {
    title: {
        color: "blue",
        fontSize: "24px",
    },
};

export default AppInlineStyle;

Q3. What are the differences between React & React Native?

Feature React React Native
Type Library Framework
Purpose Building web interfaces Building mobile applications
Platform Web browsers iOS and Android
UI HTML and CSS Native UI components (e.g., View, Text)
Deployment As web applications Through app stores (e.g., App Store, Google Play)

Q4. What is GraphQL?

  • GraphQL is a query language for APIs (Application Programming Interfaces) and a runtime for executing those queries with your existing data.

  • GraphQL and React are often used together. React components can use GraphQL queries to fetch the data required for rendering.

query {
  user(id: 1) {
    id
    name
    email
    posts {
      title
      content
    }
  }
}

Q5. What are the Top 3 ways to achieve state management? When to use what in React?

State Management Solution When to Use Reason
useState Hook Simple component-level state Ideal for applications having small components and isolated state because it is Lightweight and built into React only.
Context API Prop drilling avoidance for sharing global data. Simplifies data passing through the component tree, reducing the need for manual prop drilling.
Redux Large-scale applications with complex state. Centralized store and actions provide a predictable state management pattern, aiding in debugging and scalability.

Q6. How can you Implement Authentication in a React application? V. IMP.

  1. Send POST request POST:{username, password}

  2. Authenticate & create JWT token

  3. Return Response {JWT token}

  4. Store JWT token at local storage

  5. Request Data {JWT token: Header}

  6. Validate token signature on server-side

  7. Send Data back to client-side

  8. Display data on browser

Q7. What is the use of React Profiler?

  • React Profiler is a set of tools in React that allows developers to profile(analyze) the performance of a React application.

    // Wrap the section of code you want to profile with the React Profiler component.
    <React.Profiler id="example" onRender={callback}>
        {/* Your code to profile */}
    </React.Profiler>
    
    // Define a callback function (onRender) that will be called whenever the component tree within the Profiler is committed.
    function callback(id, phase, actualDuration, baseDuration, startTime, commitTime) {
        // Process profiling data
        // Start time, End Time, Execution Time
    }

Q8. What is the difference between fetch & axios for api calls in React?

Feature fetch Axios
Dependency Built-in JavaScript function Third-party library
Promise Support Returns Promises Returns Promises
Interceptors No support Supports interceptors
Complexity Simpler for basic HTTP requests More features for advanced use cases

fetch

fetch("https://api.example.com/data")
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.error("Error:", error));

axios

// Installation command: npm install axios
import axios from "axios";
axios
    .get("https://api.example.com/data")
    .then((response) => console.log(response.data))
    .catch((error) => console.error("Error:", error));

Q9. What are the popular Testing Libraries for React?

  • Jest

  • React Testing Library

  • Enzyme

  • Cypress

Q10. How can you Optimize Performance in a React application? V. IMP.

Technique Purpose
Memoization with useMemo and useCallback Use this hooks to memoize values and, reducing unnecessary recalculations.
Optimizing Renders with React.Fragment Use it to avoid unnecessary wrapper elements that could cause additional DOM nodes.
Lazy Loading with React.lazy Use it to load components lazily, reducing the initial bundle size and improving initial loading performance.
Code Splitting Employ code splitting to divide your application into smaller chunks that are loaded on demand, improving initial load times.
Optimizing Images and Assets Compress and optimize images, use responsive images, and leverage lazy loading for images to reduce network and rendering overhead.

Q11. Explain Reactive Programming with example?

Reactive Programming

  • A programming paradigm that focuses on reacting to changes and events in a declarative and asynchronous manner.

Declarative Programming

  • A programming style where you write the code for what you want to achieve, rather than specifying step-by-step how to achieve it.
  • Example: JSX in React has declarative syntax.

Asynchronous

  • An action that does not block other actions.

Q12. In how many ways can we implement Reactive Programming in React?

Concept Description
State and Props Reacting to changes in local component state and passing data reactively through props.
React Hooks Leveraging useState and useEffect hooks for managing state and side effects in functional components.
Event Handling Reacting to user interactions through event handling and updating state accordingly.
Context API Sharing and managing global state reactively across components using the Context API.
Redux Using state management libraries like Redux for managing complex application state reactively.
Component Lifecycle Methods Using class components and lifecycle methods for handling side effects and updates.
Async/Await Utilizing async/await syntax for handling asynchronous operations reactively.
RxJS and Observables Leveraging RxJS for handling asynchronous operations and data streams in a reactive manner.

Q13. How to pass data from child component to parent Component in React?

Parent provides a callback function to child and then child component can then invoke this callback to pass data back to the parent.

const ParentComponent = () => {
  // Callback to receive data from the child
  const callback = (data) => {
    console.log("Data from Child:", data);
  };

  return (
    <div>
      {/* Pass the callback to the child */}
      <ChildComponent fromChild={callback} />
    </div>
  );
};

export default ParentComponent
const ChildComponent = ({ fromChild }) => {
  // No local state in the child component

  const dataToParent = () => {
    // Directly pass the input value to the parent
    fromChild(document.getElementById("inputField").value);
  };

  return (
    <div>
      <input type="text" id="inputField" />
      <button onClick={dataToParent}>Send</button>
    </div>
  );
};

export default ChildComponent