All Interview Questions
About Lesson

Q1. What are state and props in react and how they are different, explain by writing a small code?

Ans: —————————————————————————-

State  : State refers to the internal data of a component that can change over time. It is managed within the component itself using the useState hook or by extending the React.Component class and using this.state. State changes trigger re-renders of the component. Props props (short for properties) are used to pass data from a parent component to a child component. They are immutable and cannot be changed by the child component. Props are passed down from parent to child as attributes and are accessed using the props object in the child component. Here’s a simple code example to illustrate the difference:

import React, { useState } from ‘react’;

Here’s a simple code example to illustrate the difference:

———————————————————————————

import React, { useState } from ‘react’;

const ParentComponent = () => {
    const [count, setCount] = useState(0); // state

    return (
        <div>
            {/* props */}
            <ChildComponent count={count} />
        </div>
    );
};

const ChildComponent = (props) => {
    return (
        <div>
            Count: {props.count}
        </div>
    );
};

export default ParentComponent;

———————————————————————————

Q2. What are the steps that React takes to convert JSX into actual output for the browser, ignoring all the internal optimization steps?

Ans: —————————————————————————-

React follows these steps to convert JSX into actual output for the browser:

  • Parsing: The JSX code is parsed into a tree-like structure called the “Abstract Syntax Tree” (AST).
  • Transformation: The AST is transformed into a plain JavaScript object, which represents the structure of the React elements.
  • Render: React uses this object to generate the actual output (HTML elements) that will be rendered in the browser.

Q3. How does React perform effective DOM updates? Explain everything step by step?

Ans: —————————————————————————-

React performs effective DOM updates through a process called “reconciliation.” Here are the steps:

  • Render: When state or props change, React re-renders the component and updates the virtual DOM.
  • Diffing Algorithm: React then compares the new virtual DOM with the previous one to identify the differences (or “diffs”) between them.
  • Minimal Updates: React determines the minimal set of DOM operations needed to update the actual DOM based on the differences identified.
  • DOM Updates: Finally, React updates the actual DOM with the minimal set of changes, resulting in efficient and effective updates.

Q4. What are custom hooks in React?

Ans: —————————————————————————-

Custom hooks in React are JavaScript functions that leverage the React hooks API (such as useState, useEffect, etc.) to encapsulate and reuse logic across multiple components. They follow the naming convention of starting with “use” and can accept arguments and return values.

Q5. What are the rules needed to follow while using React hooks?

Ans: —————————————————————————-

Rules for using React hooks:

  • Hooks should only be called at the top level of a React functional component or custom hook, not inside loops, conditions, or nested functions.
  • Hooks should be called unconditionally in the same order on every render.
  • Custom hooks should always start with “use” to adhere to the naming convention.
  • Hooks cannot be called from regular JavaScript functions.

Q6. What is debouncing?

Ans: —————————————————————————-

Debouncing is a technique used to optimize performance by delaying the execution of a function until after a certain period of inactivity. It is commonly used in scenarios like handling user input, where you want to wait for a pause in typing before triggering an action.

Q7. Create a useDebounce() hook that accepts a value and delay and only returns the updated value after a given delay?

Ans: —————————————————————————-

Here’s an example of a useDebounce hook:

import { useState, useEffect } from ‘react’;

const useDebounce = (value, delay) => {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
        const timeoutId = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);

        return () => clearTimeout(timeoutId);
    }, [value, delay]);

    return debouncedValue;
};

export default useDebounce;

———————————————————————————

Q8. Explain memoization in the context of React and ways to do memoization?

Ans: —————————————————————————-

Memoization in React involves caching the results of expensive function calls and reusing them when the same inputs occur again. This can help improve performance by avoiding unnecessary re-computation.

Q9. What is the difference between react.memo and useMemo?

Ans: ————————————————————————-

react.memo: react.memo is a higher-order component that memoizes a functional component based on its props. It prevents unnecessary re-renders by comparing the previous and current props. >useMemo: useMemo is a hook that memoizes the result of a function call and returns the memoized value. It is used to optimize expensive calculations inside functional components.

Q10. Create pagination logic?

Ans: —————————————————————————-

Pagination logic typically involves keeping track of the current page number, the number of items per page, and calculating the start and end indices of the items to display on each page.

Q11. Implement sorting logic?

Ans: —————————————————————————-

Sorting logic involves comparing elements in a list based on a certain criterion (e.g., alphabetical order, numerical order) and rearranging them accordingly. 

———————————————————————————

const items = [5, 2, 8, 1, 9];

// Sorting items in ascending order
const sortedItems = items.sort((a, b) => a – b);
console.log(sortedItems); // Output: [1, 2, 5, 8, 9]

// Sorting items in descending order
const sortedItemsDescending = items.sort((a, b) => b – a);
console.log(sortedItemsDescending); // Output: [9, 8, 5, 2, 1]

——————————————————————————— 

Q12. Write a timer that implements a timer. The component should display the elapsed time in minutes and seconds, formatted as “MM:SS”. The timer should start at 0 and increase by 1 second every second.?

Ans: —————————————————————————-

Here’s an example of a timer component that displays elapsed time in “MM:SS” format:

 ———————————————————————————

import React, { useState, useEffect } from ‘react’;
const Timer = () => {
    const [time, setTime] = useState(0);
    useEffect(() => {
        const intervalId = setInterval(() => {
            setTime(prevTime => prevTime + 1);
        }, 1000);
        return () => clearInterval(intervalId);
    }, []);
    const formattedTime = new Date(time * 1000).toISOString().substr(14, 5);
    return (
        <div>
            Elapsed Time: { formattedTime }
        </div>
    );
};
export default Timer;

———————————————————————————

Q13. Explain the typical data flow in an application made using React and Redux, and also with a diagram?

Ans: —————————————————————————-

In a React and Redux application, the typical data flow involves the following steps:

  1. Component Interaction: Components in the React application trigger actions by interacting with the user or receiving data from external sources.
  2. Dispatch: Components dispatch actions to the Redux store using action creators. These actions are plain JavaScript objects that describe the intention to change the state.
  3. Reducer Handling: Reducers in the Redux store receive these actions and update the state of the application accordingly. Reducers are pure functions that take the current state and an action as arguments and return a new state.
  4. State Update: After the reducer updates the state, the Redux store notifies all subscribed components about the state change.
  5. Component Re-render: Components subscribed to the Redux store receive the updated state as props and re-render based on the new data.

Q14. Create the structure of the Redux store for a checkout cart with a coupon code?

Ans: —————————————————————————-

 Structure of Redux Store for Checkout Cart with Coupon Code:

 ———————————————————————————

const initialState = {
    cart: [],
    couponCode: ”
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case ‘ADD_TO_CART’:
            return {
                …state,
                cart: […state.cart, action.payload]
            };
        case ‘APPLY_COUPON’:
            return {
                …state,
                couponCode: action.payload
            };
        default:
            return state;
    }
};

export default reducer;

——————————————————————————— 

This reducer manages the state of a checkout cart with items and a coupon code. Actions like adding items to the cart and applying a coupon code are dispatched to update the state accordingly.

© GeekySanjay