Title: Javascript / Interview / SRIQ - Reactjs interview questions - sudheer jonna / Part I - Fundamentals / Chapter 8 - Miscellaneous

Front: What are the differences between page router and app router in nextjs?
Back: The Page Router and App Router are two different routing systems in Next.js, with the App Router being the newer and more feature-rich option. Let's compare them:
1. Structure:
  - Page Router: Uses a file-system based routing in the pages directory.
  - App Router: Uses a new app directory with a more flexible file-system based routing.
2. Rendering Model:
  - Page Router: Primarily uses client-side rendering with options for server-side rendering.
  - App Router: Defaults to server-side rendering with client-side rendering as an option.
3. Data Fetching:
  - Page Router: Uses methods like getServerSideProps, getStaticProps, and getInitialProps.
  - App Router: Introduces new data fetching methods within React components, supporting both client and server components.
4. Layouts:
  - Page Router: Requires manual implementation of layouts, often using Higher Order Components or custom _app.js files.
  - App Router: Has built-in support for nested layouts using layout.js files.
5. Loading UI:
  - Page Router: Requires manual implementation of loading states.
  - App Router: Provides built-in support for loading UI with loading.js files.
6. Error Handling:
  - Page Router: Uses custom error pages (e.g., 404.js, 500.js).
  - App Router: Introduces error.js files for more granular error handling.
7. Static and Dynamic Rendering:
  - Page Router: Configured through separate functions like getStaticProps and getServerSideProps.
  - App Router: Uses a single fetch function with caching options to determine rendering method.
8. Middleware:
  - Page Router: Middleware applies to all routes.
  - App Router: Allows more granular middleware application, including per-route basis.
9. Route Groups:
  - Page Router: Does not have a concept of route groups.
  - App Router: Introduces route groups for better organization without affecting the URL structure.
10. Parallel Routes:
  - Page Router: Does not support parallel routes.
  - App Router: Allows rendering multiple pages in the same layout simultaneously.
Let's illustrate some of these differences with code examples:
// Page Router Example
// pages/index.js
import { useState } from 'react'
export default function Home() {
  const [count, setCount] = useState(0)
  return (
    <div>
      <h1>Welcome to my app</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  )
}
// pages/about.js
export default function About() {
  return <h1>About Page</h1>
}
// App Router Example
// app/page.js
export default function Home() {
  return (
    <div>
      <h1>Welcome to my app</h1>
      <ClientComponent />
    </div>
  )
}
// app/ClientComponent.js
'use client'
import { useState } from 'react'
export default function ClientComponent() {
  const [count, setCount] = useState(0)
  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </>
  )
}
// app/about/page.js
export default function About() {
  return <h1>About Page</h1>
}
// app/layout.js
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
// app/loading.js
export default function Loading() {
  return <p>Loading...</p>
}
// app/error.js
'use client'
export default function Error({ error, reset }) {
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  )
}
Key observations from these examples:
1. In the Page Router, all components are client-side by default. In the App Router, components are server-side by default, and we use the 'use client' directive for client-side components.
2. The App Router introduces new files like layout.js, loading.js, and error.js for handling common patterns.
3. The file structure in the app directory directly corresponds to the URL structure, similar to the pages directory but with more flexibility.
4. The App Router separates the layout (layout.js) from the page content (page.js), allowing for more reusable and maintainable code.
The App Router is generally recommended for new projects due to its improved performance and developer experience. However, the Page Router is still supported and may be preferred for certain use cases or when maintaining existing projects.

Front: When to use client and server components?
Back: You can efficiently build nextjs application if you are aware about which part of the application needs to use client components and which other parts needs to use server components. The common cases of both client and server components are listed below:
Client components:
1. Whenever your need to add interactivity and event listeners such as onClick(), onChange(), etc to the pages
2. If you need to use State and Lifecycle Effects like useState(), useReducer(), useEffect() etc.
3. If there is a requirement to use browser-only APIs.
4. If you need to implement custom hooks that depend on state, effects, or browser-only APIs.
5. There are React Class components in the pages.
Server components:
1. If the component logic is about data fetching.
2. If you need to access backend resources directly.
3. When you need to keep sensitive information((access tokens, API keys, etc) ) on the server.
4. If you want reduce client-side JavaScript and placing large dependencies on the server.

Front: What are the use cases of useContext hook?
Back: Some of the common use cases of useContext are listed below,
1. Theme customizations: The useContext hook can be used to manage and apply custom themes for an application. That means it allows users to personalize the appearance of the application.
2. Support localization: The context hook is helpful to implement localization by providing translated strings to components based on the user's language/locale preference.
3. User authentication: It can be used to manage user authentication or session status and display user specific information with in components.

Front: How does context works using useContext hook?
Back: The Context API in React, along with the useContext hook, provides a way to share data across multiple components without explicitly passing props through each level of the component tree. This is particularly useful for passing global data or for cases where many components need access to the same data.
Here's an overview of how context works with the useContext hook:
1. Create a context:
First, you create a context using React.createContext().
2. Provide the context:
Wrap the parent component with a Context Provider to make the context available to all child components.
3. Consume the context:
Use the useContext hook in any child component to access the context value.
Let's illustrate this with a simple example:
import React, { createContext, useContext, useState } from 'react';
// Step 1: Create a context
const ThemeContext = createContext();
// Step 2: Create a provider component
const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');
  const toggleTheme = () => {
    setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
  };
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};
// Step 3: Create components that use the context
const ThemedButton = () => {
  const { theme, toggleTheme } = useContext(ThemeContext);
  return (
    <button
      onClick={toggleTheme}
      style={{
        backgroundColor: theme === 'light' ? '#fff' : '#333',
        color: theme === 'light' ? '#333' : '#fff'
      }}
    >
      Toggle Theme
    </button>
  );
};
const ThemedText = () => {
  const { theme } = useContext(ThemeContext);
  return (
    <p style={{ color: theme === 'light' ? '#333' : '#fff' }}>
      Current theme: {theme}
    </p>
  );
};
// Step 4: Use the provider to wrap the app
const App = () => {
  return (
    <ThemeProvider>
      <div>
        <h1>Theme Example</h1>
        <ThemedText />
        <ThemedButton />
      </div>
    </ThemeProvider>
  );
};
export default App;
Let's break down how this works:
1. We create a ThemeContext using createContext().
2. The ThemeProvider component:
  - Manages the theme state.
  - Provides a function to toggle the theme.
  - Wraps its children with ThemeContext.Provider, passing the theme state and toggle function as the context value.
3. Child components (ThemedButton and ThemedText):
  - Use the useContext hook to access the theme context.
  - Can read the current theme and call the toggle function without these being passed as props.
4. The App component wraps everything in ThemeProvider, making the theme context available throughout the app.
Key benefits of using context with useContext:
1. Avoids prop drilling: You don't need to pass props through intermediate components.
2. Centralized state management: Useful for global states like themes, user authentication, language preferences, etc.
3. Component reusability: Components can be more easily reused as they're not tightly coupled to their data source.
4. Performance: Can potentially improve performance by reducing re-renders of intermediate components.
However, it's important to note that context should not be used for every type of state or prop. It's best suited for global or widely-used data. For local state or props that are only used by a few closely related components, regular state management or prop passing is often more appropriate.

Front: How do you compare useState and useReducer?
Back: Comparing useState and useReducer is a great way to understand when to use each hook. Let's break down the key differences and use cases:
1. Complexity of state logic:
  - useState: Best for simple state management with independent states.
  - useReducer: Preferable for complex state logic, especially when state changes are interdependent.
2. State structure:
  - useState: Typically used for primitive values or simple objects.
  - useReducer: Better for managing more complex state objects with multiple sub-values.
3. Predictability:
  - useState: Updates can be scattered across multiple event handlers.
  - useReducer: All state transitions are centralized in the reducer function, making them more predictable.
4. Code organization:
  - useState: Can lead to cluttered components with multiple state updates.
  - useReducer: Helps separate state logic from rendering logic, potentially leading to cleaner components.
5. Testing:
  - useState: State changes are typically tested through component rendering.
  - useReducer: Reducer functions are pure and can be easily unit tested in isolation.
6. Performance:
  - useState: Might cause unnecessary re-renders if not optimized properly.
  - useReducer: Can be more efficient for complex state updates, as React can optimize based on action types.
7. Learning curve:
  - useState: Simpler and more intuitive for beginners.
  - useReducer: Requires understanding of reducers and actions, which might be challenging for newcomers.
8. Debugging:
  - useState: State changes can be harder to track in complex scenarios.
  - useReducer: Easier to debug as all state changes are defined in one place and triggered by specific actions.
Let's illustrate this with a simple example comparing both approaches:
import React, { useState, useReducer } from 'react';
// useState example
const CounterWithState = () => {
    const [count, setCount] = useState(0);
    const increment = () => setCount((prevCount) => prevCount + 1);
    const decrement = () => setCount((prevCount) => prevCount - 1);
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={increment}>+</button>
            <button onClick={decrement}>-</button>
        </div>
    );
};
// useReducer example
const counterReducer = (state, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { count: state.count + 1 };
        case 'DECREMENT':
            return { count: state.count - 1 };
        default:
            return state;
    }
};
const CounterWithReducer = () => {
    const [state, dispatch] = useReducer(counterReducer, { count: 0 });
    return (
        <div>
            <p>Count: {state.count}</p>
            <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
            <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
        </div>
    );
};
In this example:
1. The CounterWithState component uses useState for a simple counter. State updates are done directly in the event handlers.
2. The CounterWithReducer component uses useReducer for the same functionality. State updates are defined in the reducer function and triggered by dispatching actions.
For this simple counter, useState is probably sufficient. However, if we were to add more complex logic (e.g., limiting the count range, adding a reset function, or incorporating multiple related states), useReducer would become more advantageous.
In general:
- Use useState for independent pieces of state/simple state updates.
- Use useReducer for complex state logic, especially when next state depends on previous state, or when you have multiple sub-values.

Front: What is useReducer hook? Can you describe its usage?
Back: The useReducer hook is a React hook that provides an alternative to useState for managing complex state logic in functional components. It's particularly useful when you have state transitions that depend on the previous state or when the next state is determined by multiple sub-values.
Here's a brief overview of useReducer:
1. Basic structure:
const [state, dispatch] = useReducer(reducer, initialState);
2. Components:
  - state: The current state value
  - dispatch: A function to send actions to update the state
  - reducer: A pure function that takes the current state and an action, and returns the new state
  - initialState: The initial state value
3. Usage:
import React, { useReducer } from 'react';
// Reducer function
const counterReducer = (state, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { count: state.count + 1 };
        case 'DECREMENT':
            return { count: state.count - 1 };
        default:
            return state;
    }
};
const Counter = () => {
    // Using useReducer
    const [state, dispatch] = useReducer(counterReducer, { count: 0 });
    return (
        <div>
            Count: {state.count}
            <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
            <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
        </div>
    );
};
export default Counter;
In this example:
1. We define a counterReducer function that specifies how the state should change in response to different actions.
2. The useReducer hook is called with the reducer function and an initial state.
3. We use the dispatch function to send actions to the reducer, which then updates the state.
4. The component re-renders with the new state when an action is dispatched.
Key benefits of useReducer:
1. Centralized state logic: All state update logic is contained in the reducer function.
2. Predictable state changes: The reducer must return a new state for any given current state and action.
3. Easier testing: Reducer functions are pure and can be easily unit tested.
4. Complex state transitions: Useful for managing state that involves multiple sub-values or when the next state depends on the previous one.
5. Performance optimization: Can be more efficient than useState for complex state logic.

Front: What are the guidelines to be followed for writing reducers?
Back: There are two guidelines to be taken care while writing reducers in your code.
1. Reducers must be pure without mutating the state. That means, same input always returns the same output. These reducers run during rendering time similar to state updater functions. So these functions should not send any requests, schedule time outs and any other side effects.
2. Each action should describe a single user interaction eventhough there are multiple changes applied to data. For example, if you "reset" registration form which has many user input fields managed by a reducer, it is suggested to send one "reset" action instead of creating separate action for each fields. The proper ordering of actions should reflect the user interactions in the browser and it helps a lot for debugging purpose.

Front: Can I use keys for non-list items?
Back: Keys are primarily used for rendering list items but they are not just for list items. You can also use them React to distinguish components. By default, React uses order of the components in

Front: What will happen by defining nested function components?
Back: Technically it is possible to write nested function components but it is not suggested to write nested function definitions. Because it leads to unexpected bugs and performance issues.

Front: What are the preferred and non-preferred array operations for updating the state?
Back: The below table represent preferred and non-preferred array operations for updating the component state.
Action | Preferred | Non-preferred
Adding | concat, […arr] | push, unshift
Removing | filter, slice | pop, shift, splice
Replacing | map | splice, arr[i] = someValue
sorting | copying to new array | reverse, sort
If you use Immer library then you can able to use all array methods without any problem.

Front: What are the benefits of preventing the direct state mutations?
Back: Preventing direct state mutations in React offers several important benefits:
1. Predictability: Immutable state makes it easier to track and predict how your application's state changes over time. This leads to more predictable behavior and fewer bugs.
2. Performance optimization: React relies on comparing the previous and current state to determine if a re-render is necessary. Immutable updates allow for more efficient comparisons, potentially improving performance.
3. Easier debugging: When state is immutable, you can more easily track the history of state changes, making it simpler to find and fix bugs.
4. Pure components: Immutable state enables the use of pure components, which can lead to performance improvements through memoization.
5. Time-travel debugging: Tools like Redux DevTools can provide time-travel debugging capabilities when state is immutable, allowing developers to move backwards and forwards through state changes.
6. Concurrency: As React moves towards concurrent rendering with features like React Fiber, immutable updates become even more important for ensuring consistent behavior.
7. Undo/Redo functionality: Immutable state makes it easier to implement undo/redo features in your application.
8. Better testing: Immutable state simplifies unit testing as you can be sure that your test cases aren't inadvertently modifying shared state.

Front: How do you use immer library for state updates?
Back: Immer library enforces the immutability of state based on copy-on-write mechanism. It uses JavaScript proxy to keep track of updates to immutable states. Immer has 3 main states as below,
1. Current state: It refers to actual state
2. Draft state: All new changes will be applied to this state. In this state, draft is just a proxy of the current state.
3. Next state: It is formed after all mutations applied to the draft state
Immer can be used by following below instructions,
1. Install the dependency using npm install use-immer command
2. Replace useState hook with useImmer hook by importing at the top
3. The setter function of useImmer hook can be used to update the state.
For example, the mutation syntax of immer library simplifies the nested address object of user state as follows,
import { useImmer } from 'use-immer';
const [user, setUser] = useImmer({
    name: 'John',
    age: 32,
    address: {
        country: 'Singapore',
        postalCode: 440004,
    },
});
//Update user details upon any event
setUser((draft) => {
    draft.address.country = 'Germany';
});
The preceding code enables you to update nested objects with a conceise mutation syntax.

Front: How do you update arrays inside state?
Back: Eventhough arrays in JavaScript are mutable in nature, you need to treat them as immutable while storing them in a state. That means, similar to objects, the arrays cannot be updated directly inside state. Instead, you need to create a copy of the existing array and then set the state to use newly copied array.
To ensure that arrays are not mutated, the mutation operations like direct direct assignment(arr[1]='one'), push, pop, shift, unshift, splice etc methods should be avoided on original array. Instead, you can create a copy of existing array with help of array operations such as filter, map, slice, spread syntax etc.
For example, the below push operation doesn't add the new todo to the total todo's list in an event handler.
onClick = {
  todos.push({
    id: id+1,
    name: name
  })
}
This issue is fixed by replacing push operation with spread syntax where it will create a new array and the UI updated with new todo.
onClick = {
  [
    ...todos,
    { id: id+1, name: name }
  ]
}

Front: How do you update nested objects inside state?
Back: You cannot simply use spread syntax for all kinds of objects inside state. Because spread syntax is shallow and it copies properties for one level deep only. If the object has nested object structure, UI doesn't work as expected with regular JavaScript nested property mutation. Let's demonstrate this behavior with an example of User object which has address nested object inside of it.
const user = {
    name: 'John',
    age: 32,
    address: {
        country: 'Singapore',
        postalCode: 440004,
    },
};
If you try to update the country nested field in a regular javascript fashion(as shown below) then user profile screen won't be updated with latest value.
user.address.country = 'Germany';
This issue can be fixed by flattening all the fields into a top-level object or create a new object for each nested object and point it to it's parent object. In this example, first you need to create copy of address object and update it with the latest value. Later, the address object should be linked to parent user object something like below.
setUser({
    ...user,
    address: {
        ...user.address,
        country: 'Germany',
    },
});
This approach is bit verbose and not easy for deep hierarchical state updates. But this workaround can be used for few levels of nested objects without much hassle.

Front: How do you update objects inside state?
Back: You cannot update the objects which exists in the state directly. Instead, you should create a fresh new object (or copy from the existing object) and update the latest state using the newly created object. Eventhough JavaScript objects are mutable, you need to treat objects inside state as read-only while updating the state.
Let's see this comparison with an example. The issue with regular object mutation approach can be described by updating the user details fields of Profile component. The properties of Profile component such as firstName, lastName and age details mutated in an event handler as shown below.
import { useState } from 'react';
export default function Profile() {
    const [user, setUser] = useState({
        firstName: 'John',
        lastName: 'Abraham',
        age: 30,
    });
    function handleFirstNameChange(e) {
        user.firstName = e.target.value;
    }
    function handleLastNameChange(e) {
        user.lastName = e.target.value;
    }
    function handleAgeChange(e) {
        user.age = e.target.value;
    }
    return (
        <>
            <label>
                First name:
                <input
                    value={user.firstName}
                    onChange={handleFirstNameChange}
                />
            </label>
            <label>
                Last name:
                <input value={user.lastName} onChange={handleLastNameChange} />
            </label>
            <label>
                Age:
                <input value={user.age} onChange={handleAgeChange} />
            </label>
            <p>
                Profile:
                {person.firstName} {person.lastName} ({person.age})
            </p>
        </>
    );
}
Once you run the application with above user profile component, you can observe that user profile details won't be update upon entering the input fields.
This issue can be fixed by creating a new copy of object which includes existing properties through spread syntax(…obj) and add changed values in a single event handler itself as shown below.
handleProfileChange(e) {
  setUser({
  ...user,
    [e.target.name]: e.target.value
  });
}
The above event handler is concise instead of maintaining separate event handler for each field. Now, UI displays the updated field values as expected without an issue.

Front: What is React hydration?
Back: React hydration is used to add client-side JavaScript interactivity to pre-rendered static HTML generated by the server. It is used only for server-side rendering(SSR) to enhance the initial rendering time and make it SEO friendly application. This hydration acts as a bridge to reduce the gap between server side and client-side rendering.
After the page loaded with generated static HTML, React will add application state and interactivity by attaching all event handlers for the respective elements. Let's demonstrate this with an example.
Consider that React DOM API(using renderToString) generated HTML for <App> component which contains <button> element to increment the counter.
import {useState} from 'react';
import { renderToString } from 'react-dom/server';
export default function App() {
  const [count, setCount] = React.useState(0);
  return (
    <h1>Counter</h1>
    <button onClick={() => setCount(prevCount => prevCount + 1)}>
      {count} times
    </button>
    );
}
const html = renderToString(<App />);
The above code generates the below HTML with a header text and button component without any interactivity.
<h1>Counter</h1>
<button>
    <!-- -->0<!-- -->
    times
</button>
At this stage hydrateRoot API can be used to perform hydration by attaching onClick event handler.
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document.getElementById('root'), <App />);
After this step, you are able to run React application on server-side and hydrating the javascript bundle on client-side for smooth user experience and SEO purposes.

Front: Is it possible to prevent automatic batching?
Back: Yes, it is possible to prevent automatic batching default behavior. There might be cases where you need to re-render your component after each state update or updating one state depends on another state variable. Considering this situation, React introduced flushSync method from react-dom API for the usecases where you need to flush state updates to DOM immediately.
The usage of flushSync method within an onClick event handler will be looking like as below,
import { flushSync } from 'react-dom';
const handleClick = () => {
    flushSync(() => {
        setClicked(!clicked); //Component will create a re-render here
    });
    setCount(count + 1); // Component will create a re-render again here
};
In the above click handler, React will update DOM at first using flushSync and second time updates DOM because of the counter setter function by avoiding automatic batching.

Front: How does React batch multiple state updates?
Back: React prevents component from re-rendering for each and every state update by grouping multiple state updates within an event handler. This strategy improves the application performance and this process known as batching. The older version of React only supported batching for browser events whereas React18 supported for asynchronous actions, timeouts and intervals along with native events. This improved version of batching is called automatic batching.
Let's demonstrate this automatic batching feature with a below example.
import { useState } from 'react';
export default function BatchingState() {
    const [count, setCount] = useState(0);
    const [message, setMessage] = useState('batching');
    console.log('Application Rendered');
    const handleUsers = () => {
        fetch('https://jsonplaceholder.typicode.com/users/1').then(() => {
            // Automatic Batching re-render only once
            setCount(count + 1);
            setMessage('users fetched');
        });
    };
    return (
        <>
            <h1>{count}</h1>
            <button onClick={handleAsyncFetch}>Click Me!</button>
        </>
    );
}
The preceding code updated two state variables with in an event handler. However, React will perform automatic batching feature and the component will be re-rendered only once for better performance.

Front: How does React updates screen in an application?
Back: React updates UI in three steps,
1. Triggering or initiating a render: The component is going to triggered for render in two ways.
  1. Initial render: When the app starts, you can trigger the initial render by calling creatRoot with the target DOM node followed by invoking component's render method. For example, the following code snippet renders App component on root DOM node.
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
  1. Re-render when the state updated: When you update the component state using the state setter function, the componen't state automatically queues for a render.
2. Rendering components: After triggering a render, React will call your components to display them on the screen. React will call the root component for initial render and call the function component whose state update triggered the render. This is a recursive process for all nested components of the target component.
3. Commit changes to DOM: After calling components, React will modify the DOM for initial render using appendChild() DOM API and apply minimal necessary DOM updates for re-renders based on differences between rerenders.

Front: What are capture phase events?
Back: The onClickCapture React event is helpful to catch all the events of child elements irrespective of event propagation logic or even if the events propagation stopped. This is useful if you need to log every click events for analytics purpose.
For example, the below code triggers the click event of parent first followed by second level child eventhough leaf child button elements stops the propagation.
<div onClickCapture={() => alert('parent')}>
    <div onClickCapture={() => alert('child')}>
        <button onClick={(e) => e.stopPropagation()} />
        <button onClick={(e) => e.stopPropagation()} />
    </div>
</div>
The event propagation for the above code snippet happens in the following order:
1. It travels downwards in the DOM tree by calling all onClickCapture event handlers.
2. It executes onClick event handler on the target element.
3. It travels upwards in the DOM tree by call all onClick event handlers above to it.

Front: How do you prevent mutating array variables?
Back: The preexisting variables outside of the function scope including state, props and context leads to a mutation and they result in unpredictable bugs during the rendering stage. The below points should be taken care while working with arrays variables.
1. You need to take copy of the original array and perform array operations on it for the rendering purpose. This is called local mutation.
2. Avoid triggering mutation methods such as push, pop, sort and reverse methods on original array. It is safe to use filter, map and slice method because they create a new array.

Front: What is the reason behind multiple JSX tags to be wrapped?
Back: Behind the scenes, JSX is transformed into plain javascript objects. It is not possible to return two or more objects from a function without wrapping into an array. This is the reason you can't simply return two or more JSX tags from a function without
wrapping them into a single parent tag or a Fragment.

Front: What are the rules of JSX?
Back: The below 3 rules needs to be followed while using JSX in a react application.
1. Return a single root element:
If you are returning multiple elements from a component, wrap them in a single parent element. Otherwise you will receive the below error in your browser console.
html Adjacent JSX elements must be wrapped in an enclosing tag.
2. All the tags needs to be closed:
Unlike HTML, all tags needs to closed explicitly with in JSX. This rule applies for self-closing tags(like hr, br and img tags) as well.
3. Use camelCase naming:
It is suggested to use camelCase naming for attributes in JSX. For example, the common attributes of HTML elements such as class, tabindex will be used as className and tabIndex.
Note: There is an exception for aria-* and data-* attributes which should be lower cased all the time.

Front: Why does strict mode render twice in React?
Back: StrictMode renders components twice in development mode(not production) in order to detect any problems with your code and warn you about those problems. This is used to detect accidental side effects in the render phase. If you used create-react-app development tool then it automatically enables StrictMode by default.
const root = createRoot(document.getElementById('root'));
root.render(
    <StrictMode>
        <App />
    </StrictMode>,
);
If you want to disable this behavior then you can simply remove strict mode.
const root = createRoot(document.getElementById('root'));
root.render(<App />);
To detect side effects the following functions are invoked twice:
1. Function component bodies, excluding the code inside event handlers.
2. Functions passed to useState, useMemo, or useReducer (any other Hook)
3. Class component's constructor, render, and shouldComponentUpdate methods
4. Class component static getDerivedStateFromProps method
5. State updater functions

Front: What is the benefit of strict mode?
Back: The will be helpful in the below cases,
1. To find the bugs caused by impure rendering where the components will re-render twice.
2. To find the bugs caused by missing cleanup of effects where the components will re-run effects one more extra time.
3. Identifying components with unsafe lifecycle methods.
4. Warning about legacy string ref API usage.
5. Detecting unexpected side effects.
6. Detecting legacy context API.
7. Warning about deprecated findDOMNode usage

Front: What is strict mode in React?
Back: React.StrictMode is a useful component for highlighting potential problems in an application. Just like <Fragment>, <StrictMode> does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for development mode only.
import { StrictMode } from 'react';
function App() {
    return (
        <div>
            <Header />
            <StrictMode>
                <div>
                    <ComponentOne />
                    <ComponentTwo />
                </div>
            </StrictMode>
            <Header />
        </div>
    );
}
In the example above, the strict mode checks apply to <ComponentOne> and <ComponentTwo> components only. i.e., Part of the application only.
Note: Frameworks such as NextJS has this flag enabled by default.

Front: What are the differences between Functional and Class Components?
Back: There are two different ways to create components in ReactJS. The main differences are listed down as below,
1. Syntax:
The class components uses ES6 classes to create the components. It uses render function to display the HTML content in the webpage.
The syntax for class component looks like as below.
class App extends React.Component {
    render() {
        return <h1>This is a class component</h1>;
    }
}
Note: The Pascal Case is the recommended approach to provide naming to a component.
Functional component has been improved over the years with some added features like Hooks. Here is a syntax for functional component.
function App() {
    return (
        <div className='App'>
            <h1>Hello, I'm a function component</h1>
        </div>
    );
}
2. State:
State contains information or data about a component which may change over time.
In class component, you can update the state when a user interacts with it or server updates the data using the setState() method. The initial state is going to be assigned in the Constructor() method using the this.state object and it is possible to assign different data types such as string, boolean, numbers, etc.
A simple example showing how we use the setState() and constructor():
class App extends Component {
    constructor() {
        super();
        this.state = {
            message: 'This is a class component',
        };
    }
    updateMessage() {
        this.setState({
            message: 'Updating the class component',
        });
    }
    render() {
        return (
            <>
                <h1>{this.state.message}</h1>
                <button
                    onClick={() => {
                        this.updateMessage();
                    }}
                >
                    Click!!
                </button>
            </>
        );
    }
}
You didn't use state in functional components because it was only supported in class components. But over the years hooks have been implemented in functional components which enables to use state too.
The useState() hook can used to implement state in functional components. It returns an array with two items: the first item is current state and the next one is a function (setState) that updates the value of the current state.
Let's see an example to demonstrate the state in functional components,
function App() {
    const [message, setMessage] = useState('This is a functional component');
    const updateMessage = () => {
        setMessage('Updating the functional component');
    };
    return (
        <div className='App'>
            <h1>{message} </h1>
            <button onClick={updateMessage}>Click me!!</button>
        </div>
    );
}
3. Props:
Props are referred to as "properties". The props are passed into React component just like arguments passed to a function. In other words, they are similar to HTML attributes.
The props are accessible in child class component using this.props as shown in below example,
class Child extends React.Component {
    render() {
        return (
            <h1>
                {' '}
                This is a functional component and component name is {
                    this.props.name
                }{' '}
            </h1>
        );
    }
}
class Parent extends React.Component {
    render() {
        return (
            <div className='Parent'>
                <Child name='First child component' />
                <Child name='Second child component' />
            </div>
        );
    }
}
Props in functional components are similar to that of the class components but the difference is the absence of 'this' keyword.
function Child(props) {
    return (
        <h1>This is a child component and the component name is{props.name}</h1>
    );
}
function Parent() {
    return (
        <div className='Parent'>
            <Child name='First child component' />
            <Child name='Second child component' />
        </div>
    );
}

Front: What are the differences between useEffect and useLayoutEffect hooks?
Back: useEffect and useLayoutEffect are both React hooks that can be used to synchronize a component with an external system, such as a browser API or a third-party library. However, there are some key differences between the two:
- Timing: useEffect runs after the browser has finished painting, while useLayoutEffect runs synchronously before the browser paints. This means that useLayoutEffect can be used to measure and update layout in a way that feels more synchronous to the user.
- Browser Paint: useEffect allows browser to paint the changes before running the effect, hence it may cause some visual flicker. useLayoutEffect synchronously runs the effect before browser paints and hence it will avoid visual flicker.
- Execution Order: The order in which multiple useEffect hooks are executed is determined by React and may not be predictable. However, the order in which multiple useLayoutEffect hooks are executed is determined by the order in which they were called.
- Error handling: useEffect has a built-in mechanism for handling errors that occur during the execution of the effect, so that it does not crash the entire application. useLayoutEffect does not have this mechanism, and errors that occur during the execution of the effect will crash the entire application.
In general, it's recommended to use useEffect as much as possible, because it is more performant and less prone to errors. useLayoutEffect should only be used when you need to measure or update layout, and you can't achieve the same result using useEffect.

Front: What is a wrapper component?
Back: A wrapper in React is a component that wraps or surrounds another component or group of components. It can be used for a variety of purposes such as adding additional functionality, styling, or layout to the wrapped components.
For example, consider a simple component that displays a message:
const Message = ({ text }) => {
    return <p>{text}</p>;
};
We can create a wrapper component that will add a border to the message component:
const MessageWrapper = (props) => {
    return (
        <div style={{ border: '1px solid black' }}>
            <Message {...props} />
        </div>
    );
};
Now we can use the MessageWrapper component instead of the Message component and the message will be displayed with a border:
<MessageWrapper text='Hello World' />
Wrapper component can also accept its own props and pass them down to the wrapped component, for example, we can create a wrapper component that will add a title to the message component:
const MessageWrapperWithTitle = ({ title, ...props }) => {
    return (
        <div>
            <h3>{title}</h3>
            <Message {...props} />
        </div>
    );
};
Now we can use the MessageWrapperWithTitle component and pass title props:
<MessageWrapperWithTitle title='My Message' text='Hello World' />
This way, the wrapper component can add additional functionality, styling, or layout to the wrapped component while keeping the wrapped component simple and reusable.

Front: What is the difference between useState and useRef hook?
Back: 1. useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes.
Essentially, useRef is like a “box” that can hold a mutable value in its (.current) property.
2. useState allows us to update the state inside components. While useRef allows referencing DOM elements.

Front: What is prop drilling?
Back: Prop Drilling is the process by which you pass data from one component of the React Component tree to another by going through other components that do not need the data but only help in passing it around.

Front: What are React Server components?
Back: React Server Component is a way to write React component that gets rendered in the server-side with the purpose of improving React app performance. These components allow us to load components from the backend.
Note: React Server Components is still under development and not recommended for production yet.

Front: How is the new JSX transform different from old transform??
Back: The new JSX transform doesn’t require React to be in scope. i.e, You don't need to import React package for simple scenarios.
Let's take an example to look at the main differences between the old and the new transform,
Old Transform:
import React from 'react';
function App() {
    return <h1>Good morning!!</h1>;
}
Now JSX transform convert the above code into regular JavaScript as below,
import React from 'react';
function App() {
    return React.createElement('h1', null, 'Good morning!!');
}
New Transform:
The new JSX transform doesn't require any React imports
function App() {
    return <h1>Good morning!!</h1>;
}
Under the hood JSX transform compiles to below code
import { jsx as _jsx } from 'react/jsx-runtime';
function App() {
    return _jsx('h1', { children: 'Good morning!!' });
}
Note: You still need to import React to use Hooks.

Front: What are the benefits of new JSX transform?
Back: There are three major benefits of new JSX transform,
1. It is possible to use JSX without importing React packages
2. The compiled output might improve the bundle size in a small amount
3. The future improvements provides the flexibility to reduce the number of concepts to learn React.

Front: How do you make sure that user remains authenticated on page refresh while using Context API State Management?
Back: When a user logs in and reload, to persist the state generally we add the load user action in the useEffect hooks in the main App.js. While using Redux, loadUser action can be easily accessed.
App.js
import { loadUser } from '../actions/auth';
store.dispatch(loadUser());
- But while using Context API, to access context in App.js, wrap the AuthState in index.js so that App.js can access the auth context. Now whenever the page reloads, no matter what route you are on, the user will be authenticated as loadUser action will be triggered on each re-render.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import AuthState from './context/auth/AuthState';
ReactDOM.render(
    <React.StrictMode>
        <AuthState>
            <App />
        </AuthState>
    </React.StrictMode>,
    document.getElementById('root'),
);
App.js
const authContext = useContext(AuthContext);
const { loadUser } = authContext;
useEffect(() => {
    loadUser();
}, []);
loadUser
const loadUser = async () => {
    const token = sessionStorage.getItem('token');
    if (!token) {
        dispatch({
            type: ERROR,
        });
    }
    setAuthToken(token);
    try {
        const res = await axios('/api/auth');
        dispatch({
            type: USER_LOADED,
            payload: res.data.data,
        });
    } catch (err) {
        console.error(err);
    }
};

Front: What are the benefits of using TypeScript with ReactJS?
Back: Below are some of the benefits of using TypeScript with ReactJS,
1. It is possible to use latest JavaScript features
2. Use of interfaces for complex type definitions
3. IDEs such as VS Code was made for TypeScript
4. Avoid bugs with the ease of readability and Validation

Front: What is the difference between Imperative and Declarative in React?
Back: Imagine a simple UI component, such as a "Like" button. When you tap it, it turns blue if it was previously grey, and grey if it was previously blue.
The imperative way of doing this would be:
if (user.likes()) {
    if (hasBlue()) {
        removeBlue();
        addGrey();
    } else {
        removeGrey();
        addBlue();
    }
}
Basically, you have to check what is currently on the screen and handle all the changes necessary to redraw it with the current state, including undoing the changes from the previous state. You can imagine how complex this could be in a real-world scenario.
In contrast, the declarative approach would be:
if (this.state.liked) {
    return <blueLike />;
} else {
    return <greyLike />;
}
Because the declarative approach separates concerns, this part of it only needs to handle how the UI should look in a specific state, and is therefore much simpler to understand.

Front: What is the purpose of eslint plugin for hooks?
Back: The ESLint plugin enforces rules of Hooks to avoid bugs. It assumes that any function starting with ”use” and a capital letter right after it is a Hook. In particular, the rule enforces that,
1. Calls to Hooks are either inside a PascalCase function (assumed to be a component) or another useSomething function (assumed to be a custom Hook).
2. Hooks are called in the same order on every render.

Front: Can I use javascript urls in react16.9?
Back: Yes, you can use javascript: URLs but it will log a warning in the console. Because URLs starting with javascript: are dangerous by including unsanitized output in a tag like <a href> and create a security hole.
const companyProfile = {
    website: "javascript: alert('Your website is hacked')",
};
// It will log a warning
<a href={companyProfile.website}>More details</a>;
Remember that the future versions will throw an error for javascript URLs.

Front: What is the difference between async mode and concurrent mode?
Back: Both refers the same thing. Previously concurrent Mode being referred to as "Async Mode" by React team. The name has been changed to highlight React’s ability to perform work on different priority levels. So it avoids the confusion from other approaches to Async Rendering.

Front: What is Concurrent Rendering?
Back: The Concurrent rendering makes React apps to be more responsive by rendering component trees without blocking the main UI thread. It allows React to interrupt a long-running render to handle a high-priority event. i.e, When you enabled concurrent Mode, React will keep an eye on other tasks that need to be done, and if there's something with a higher priority it will pause what it is currently rendering and let the other task finish first. You can enable this in two ways,
// 1. Part of an app by wrapping with ConcurrentMode
<React.unstable_ConcurrentMode>
    <Something />
</React.unstable_ConcurrentMode>;
// 2. Whole app using createRoot
ReactDOM.unstable_createRoot(domNode).render(<App />);

Front: Should I learn ES6 before learning ReactJS?
Back: No, you don’t have to learn es2015/es6 to learn react. But you may find many resources or React ecosystem uses ES6 extensively. Let's see some of the frequently used ES6 features,
1. Destructuring: To get props and use them in a component
// in es 5
var someData = this.props.someData;
var dispatch = this.props.dispatch;
// in es6
const { someData, dispatch } = this.props;
2. Spread operator: Helps in passing props down into a component
// in es 5
<SomeComponent someData={this.props.someData} dispatch={this.props.dispatch} />
// in es6
<SomeComponent {...this.props} />
3. Arrow functions: Makes compact syntax
// es 5
var users = usersList.map(function (user) {
    return <li>{user.name}</li>;
});
// es 6
const users = usersList.map((user) => <li>{user.name}</li>);

Front: What are the differences between Redux and MobX?
Back: Below are the main differences between Redux and MobX,
Topic | Redux | MobX
Definition | It is a javascript library for managing the application state | It is a library for reactively managing the state of your applications
Programming | It is mainly written in ES6 | It is written in JavaScript(ES5)
Data Store | There is only one large store exist for data storage | There is more than one store for storage
Usage | Mainly used for large and complex applications | Used for simple applications
Performance | Need to be improved | Provides better performance
How it stores | Uses JS Object to store | Uses observable to store the data

Front: What is MobX?
Back: MobX is a simple, scalable and battle tested state management solution for applying functional reactive programming (TFRP). For ReactJS application, you need to install below packages,
npm install mobx --save
npm install mobx-react --save

Front: Describe about data flow in react?
Back: React implements one-way reactive data flow using props which reduce boilerplate and is easier to understand than traditional two-way data binding.

Front: Do browsers understand JSX code?
Back: No, browsers can't understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.

Front: What are typical middleware choices for handling asynchronous calls in Redux?
Back: Some of the popular middleware choices for handling asynchronous calls in Redux eco system are Redux Thunk, Redux Promise, Redux Saga.

Front: What is formik?
Back: Formik is a small react form library that helps you with the three major problems,
1. Getting values in and out of form state
2. Validation and error messages
3. Handling form submission

Front: How do you access imperative API of web components?
Back: Web Components often expose an imperative API to implement its functions. You will need to use a ref to interact with the DOM node directly if you want to access imperative API of a web component. But if you are using third-party Web Components, the best solution is to write a React component that behaves as a wrapper for your Web Component.

Front: What are the sources used for introducing hooks?
Back: Hooks got the ideas from several different sources. Below are some of them,
1. Previous experiments with functional APIs in the react-future repository
2. Community experiments with render prop APIs such as Reactions Component
3. State variables and state cells in DisplayScript.
4. Subscriptions in Rx.
5. Reducer components in ReasonReact.

Front: Why do we use array destructuring (square brackets notation) in useState?
Back: When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.
For example, the array index access would look as follows:
var userStateVariable = useState('userProfile'); // Returns an array pair
var user = userStateVariable[0]; // Access first item
var setUser = userStateVariable[1]; // Access second item
Whereas with array destructuring the variables can be accessed as follows:
const [user, setUser] = useState('userProfile');

Front: What is the stable release for hooks support?
Back: React includes a stable implementation of React Hooks in 16.8 release for below packages
1. React DOM
2. React DOM Server
3. React Test Renderer
4. React Shallow Renderer

Front: Is Hooks cover all use cases for classes?
Back: Hooks doesn't cover all use cases of classes but there is a plan to add them soon. Currently there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet.

Front: How to fetch data with React Hooks?
Back: The effect hook called useEffect can be used to fetch data from an API and to set the data in the local state of the component with the useState hook’s update function.
Here is an example of fetching a list of react articles from an API using fetch.
import React from 'react';
function App() {
    const [data, setData] = React.useState({ hits: [] });
    React.useEffect(() => {
        fetch('http://hn.algolia.com/api/v1/search?query=react')
            .then((response) => response.json())
            .then((data) => setData(data));
    }, []);
    return (
        <ul>
            {data.hits.map((item) => (
                <li key={item.objectID}>
                    <a href={item.url}>{item.title}</a>
                </li>
            ))}
        </ul>
    );
}
export default App;
A popular way to simplify this is by using the library axios.
We provided an empty array as second argument to the useEffect hook to avoid activating it on component updates. This way, it only fetches on component mount.

Front: Do I need to rewrite all my class components with hooks?
Back: No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.

Front: Is it recommended to use CSS In JS technique in React?
Back: React does not have any opinion about how styles are defined but if you are a beginner then good starting point is to define your styles in a separate *.css file as usual and refer to them using className. This functionality is not part of React but came from third-party libraries. But If you want to try a different approach(CSS-In-JS) then styled-components library is a good option.

Front: Can you list down top websites or applications using react as front end framework?
Back: Below are the top 10 websites using React as their front-end framework,
1. Facebook
2. Uber
3. Instagram
4. WhatsApp
5. Khan Academy
6. Airbnb
7. Dropbox
8. Flipboard
9. Netflix
10. PayPal

Front: How to add Bootstrap to a react application?
Back: Bootstrap can be added to your React app in a three possible ways,
1. Using the Bootstrap CDN:
This is the easiest way to add bootstrap. Add both bootstrap CSS and JS resources in a head tag.
2. Bootstrap as Dependency:
If you are using a build tool or a module bundler such as Webpack, then this is the preferred option for adding Bootstrap to your React application
npm install bootstrap
3. React Bootstrap Package:
In this case, you can add Bootstrap to our React app is by using a package that has rebuilt Bootstrap components to work particularly as React components. Below packages are popular in this category,
  1. react-bootstrap
  2. reactstrap

Front: What is the difference between Real DOM and Virtual DOM?
Back: Below are the main differences between Real DOM and Virtual DOM,
Real DOM | Virtual DOM
Updates are slow | Updates are fast
DOM manipulation is very expensive. | DOM manipulation is very easy
You can update HTML directly. | You Can’t directly update HTML
It causes too much of memory wastage | There is no memory wastage
Creates a new DOM if element updates | It updates the JSX if element update

Front: What is your favorite React stack?
Back: Even though the tech stack varies from developer to developer, the most popular stack is used in react boilerplate project code. It mainly uses Redux and redux-saga for state management and asynchronous side-effects, react-router for routing purpose, styled-components for styling react components, axios for invoking REST api, and other supported stack such as webpack, reselect, ESNext, Babel.
You can clone the project https://github.com/react-boilerplate/react-boilerplate and start working on any new react project.

Front: How do you set default value for uncontrolled component?
Back: In React, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you might want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.
render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <label>
        User Name:
        <input
          defaultValue="John"
          type="text"
          ref={this.input} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}
The same applies for select and textArea inputs. But you need to use defaultChecked for checkbox and radio inputs.

Front: What is the typical use case of portals?
Back: React portals are very useful when a parent component has overflow: hidden or has properties that affect the stacking context (e.g. z-index, position, opacity) and you need to visually “break out” of its container.
For example, dialogs, global message notifications, hovercards, and tooltips.

Front: How do you print falsy values in JSX?
Back: The falsy values such as false, null, undefined, and true are valid children but they don't render anything. If you still want to display them then you need to convert it to string. Let's take an example on how to convert to a string,
<div>My JavaScript variable is {String(myVariable)}.</div>

Front: What is windowing technique?
Back: Windowing is a technique that only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created. If your application renders long lists of data then this technique is recommended. Both react-window and react-virtualized are popular windowing libraries which provides several reusable components for displaying lists, grids, and tabular data.

Front: What are the problems of using render props with pure components?
Back: If you create a function inside a render method, it negates the purpose of pure component. Because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop. You can solve this issue by defining the render function as instance method.

Front: Must prop be named as render for render props?
Back: Even though the pattern named render props, you don’t have to use a prop named render to use this pattern. i.e, Any prop that is a function that a component uses to know what to render is technically a “render prop”. Lets take an example with the children prop for render props,
<Mouse
    children={(mouse) => (
        <p>
            The mouse position is {mouse.x}, {mouse.y}
        </p>
    )}
/>
Actually children prop doesn’t need to be named in the list of “attributes” in JSX element. Instead, you can keep it directly inside element,
<Mouse>
    {(mouse) => (
        <p>
            The mouse position is {mouse.x}, {mouse.y}
        </p>
    )}
</Mouse>
While using this above technique(without any name), explicitly state that children should be a function in your propTypes.
Mouse.propTypes = {
    children: PropTypes.func.isRequired,
};

Front: When do you need to use refs?
Back: There are few use cases to go for refs,
1. Managing focus, text selection, or media playback.
2. Triggering imperative animations.
3. Integrating with third-party DOM libraries.

Front: What are the rules covered by diffing algorithm?
Back: When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements. It covers the below rules during reconciliation algorithm,
1. Elements Of Different Types:
Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch. For example, elements <a> to <img>, or from <Article> to <Comment> of different types lead a full rebuild.
2. DOM Elements Of The Same Type:
When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes. Lets take an example with same DOM elements except className attribute,
<div className="show" title="ReactJS" />
<div className="hide" title="ReactJS" />
3. Component Elements Of The Same Type:
When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element, and calls componentWillReceiveProps() and componentWillUpdate() on the underlying instance. After that, the render() method is called and the diff algorithm recurses on the previous result and the new result.
4. Recursing On Children:
when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference. For example, when adding an element at the end of the children, converting between these two trees works well.
<ul>
  <li>first</li>
  <li>second</li>
</ul>
<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
</ul>
5. Handling keys:
React supports a key attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree. For example, adding a key can make the tree conversion efficient,
<ul>
  <li key="2015">Duke</li>
  <li key="2016">Villanova</li>
</ul>
<ul>
  <li key="2014">Connecticut</li>
  <li key="2015">Duke</li>
  <li key="2016">Villanova</li>
</ul>

Front: What is diffing algorithm?
Back: React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithms is generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n³) where n is the number of elements in the tree.
In this case, displaying 1000 elements would require in the order of one billion comparisons. This is far too expensive. Instead, React implements a heuristic O(n) algorithm based on two assumptions:
1. Two elements of different types will produce different trees.
2. The developer can hint at which child elements may be stable across different renders with a key prop.

Front: What is the purpose of default value in context?
Back: The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.
Below code snippet provides default theme value as Luna.
const MyContext = React.createContext(defaultValue);

Front: What is route based code splitting?
Back: One of the best place to do code splitting is with routes. The entire page is going to re-render at once so users are unlikely to interact with other elements in the page at the same time. Due to this, the user experience won't be disturbed.
Let us take an example of route based website using libraries like React Router with React.lazy,
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
    <Router>
        <Suspense fallback={<div>Loading...</div>}>
            <Switch>
                <Route exact path='/' component={Home} />
                <Route path='/about' component={About} />
            </Switch>
        </Suspense>
    </Router>
);
In the above code, the code splitting will happen at each route level.

Front: What is suspense component?
Back: If the module containing the dynamic import is not yet loaded by the time parent component renders, you must show some fallback content while you’re waiting for it to load using a loading indicator. This can be done using Suspense component.
For example, the below code uses suspense component,
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
    return (
        <div>
            <Suspense fallback={<div>Loading...</div>}>
                <OtherComponent />
            </Suspense>
        </div>
    );
}
As mentioned in the above code, Suspense is wrapped above the lazy component.

Front: What are loadable components?
Back: With the release of React 18, React.lazy and Suspense are now available for server-side rendering. However, prior to React 18, it was recommended to use Loadable Components for code-splitting in a server-side rendered app because React.lazy and Suspense were not available for server-side rendering. Loadable Components lets you render a dynamic import as a regular component. For example, you can use Loadable Components to load the OtherComponent in a separate bundle like this:
import loadable from '@loadable/component';
const OtherComponent = loadable(() => import('./OtherComponent'));
function MyComponent() {
    return (
        <div>
            <OtherComponent />
        </div>
    );
}
Now OtherComponent will be loaded in a separated bundle
Loadable Components provides additional benefits beyond just code-splitting, such as automatic code reloading, error handling, and preloading. By using Loadable Components, you can ensure that your application loads quickly and efficiently, providing a better user experience for your users.

Front: What is dynamic import?
Back: You can achieve code-splitting in your app using dynamic import.
Let's take an example of addition,
1. Normal Import
import { add } from './math';
console.log(add(10, 20));
1. Dynamic Import
import('./math').then((math) => {
    console.log(math.add(10, 20));
});

Front: Can I use web components in react application?
Back: Yes, you can use web components in a react application. Even though many developers won't use this combination, it may require especially if you are using third-party UI components that are written using Web Components.
For example, let us use Vaadin date picker web component as below,
import './App.css';
import '@vaadin/vaadin-date-picker';
export default function App() {
    return (
        <div className='App'>
            <vaadin-date-picker label='When were you born?'></vaadin-date-picker>
        </div>
    );
}

Front: Why are you not required to use inheritance?
Back: In React, it is recommended to use composition over inheritance to reuse code between components. Both Props and composition give you all the flexibility you need to customize a component’s look and behavior explicitly and safely.
Whereas, If you want to reuse non-UI functionality between components, it is suggested to extract it into a separate JavaScript module. Later components import it and use that function, object, or class, without extending it.

Front: What are the advantages of formik over redux form library?
Back: Below are the main reasons to recommend formik over redux form library,
1. The form state is inherently short-term and local, so tracking it in Redux (or any kind of Flux library) is unnecessary.
2. Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY SINGLE KEYSTROKE. This way it increases input latency for large apps.
3. Redux-Form is 22.5 kB minified gzipped whereas Formik is 12.7 kB

Front: What is the popular choice for form handling?
Back: Formik is a form library for react which provides solutions such as validation, keeping track of the visited fields, and handling form submission.
In detail, You can categorize them as follows,
1. Getting values in and out of form state
2. Validation and error messages
3. Handling form submission
It is used to create a scalable, performant, form helper with a minimal API to solve annoying stuff.

Front: Should keys be globally unique?
Back: The keys used within arrays should be unique among their siblings but they don’t need to be globally unique. i.e, You can use the same keys with two different arrays.
For example, the below Book component uses two arrays with different arrays,
function Book(props) {
    const index = (
        <ul>
            {props.pages.map((page) => (
                <li key={page.id}>{page.title}</li>
            ))}
        </ul>
    );
    const content = props.pages.map((page) => (
        <div key={page.id}>
            <h3>{page.title}</h3>
            <p>{page.content}</p>
            <p>{page.pageNumber}</p>
        </div>
    ));
    return (
        <div>
            {index}
            <hr />
            {content}
        </div>
    );
}

Front: What are the conditions to safely use the index as a key?
Back: There are three conditions to make sure, it is safe use the index as a key.
1. The list and items are static– they are not computed and do not change
2. The items in the list have no ids
3. The list is never reordered or filtered.

Front: How do you say that props are readonly?
Back: When you declare a component as a function or a class, it must never modify its own props.
Let us take a below capital function,
function capital(amount, interest) {
    return amount + interest;
}
The above function is called “pure” because it does not attempt to change their inputs, and always return the same result for the same inputs. Hence, React has a single rule saying "All React components must act like pure functions with respect to their props."

Front: How do you update rendered elements?
Back: You can update UI(represented by rendered element) by passing the newly created element to ReactDOM's render method.
For example, lets take a ticking clock example, where it updates the time by calling render method multiple times,
function tick() {
    const element = (
        <div>
            <h1>Hello, world!</h1>
            <h2>It is {new Date().toLocaleTimeString()}.</h2>
        </div>
    );
    ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);

Front: How JSX prevents Injection Attacks?
Back: React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.
For example, you can embed user input as below,
const name = response.potentiallyMaliciousInput;
const element = <h1>{name}</h1>;
This way you can prevent XSS(Cross-site-scripting) attacks in the application.

Front: How to prevent a function from being called multiple times?
Back: If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways,
1. Throttling: Changes based on a time based frequency. For example, it can be used using _.throttle lodash function
2. Debouncing: Publish changes after a period of inactivity. For example, it can be used using _.debounce lodash function
3. RequestAnimationFrame throttling: Changes based on requestAnimationFrame. For example, it can be used using raf-schd lodash function

Front: How do you pass an event handler to a component?
Back: You can pass event handlers and other functions as props to child components. The functions can be passed to child component as below,
function Button({ onClick }) {
    return <button onClick={onClick}>Download</button>;
}
export default function downloadExcel() {
    function handleClick() {
        alert('Downloaded');
    }
    return <Button onClick={handleClick}></Button>;
}

Front: What is NextJS and major features of it?
Back: Next.js is a popular and lightweight framework for static and server‑rendered applications built with React. It also provides styling and routing solutions. Below are the major features provided by NextJS,
1. Server-rendered by default
2. Automatic code splitting for faster page loads
3. Simple client-side routing (page based)
4. Webpack-based dev environment which supports (HMR)
5. Able to implement with Express or any other Node.js HTTP server
6. Customizable with your own Babel and Webpack configurations

Front: When component props defaults to true?
Back: If you pass no value for a prop, it defaults to true. This behavior is available so that it matches the behavior of HTML.
For example, below expressions are equivalent,
<MyInput autocomplete />
<MyInput autocomplete={true} />
Note: It is not recommended to use this approach because it can be confused with the ES6 object shorthand (example, {name} which is short for {name: name})

Front: Does React support all HTML attributes?
Back: As of React 16, both standard or custom DOM attributes are fully supported. Since React components often take both custom and DOM-related props, React uses the camelCase convention just like the DOM APIs.
Let us take few props with respect to standard HTML attributes,
<div tabIndex="-1" />      // Just like node.tabIndex DOM API
<div className="Button" /> // Just like node.className DOM API
<input readOnly={true} />  // Just like node.readOnly DOM API
These props work similarly to the corresponding HTML attributes, with the exception of the special cases. It also support all SVG attributes.

Front: What are Keyed Fragments?
Back: The Fragments declared with the explicit syntax may have keys. The general use case is mapping a collection to an array of fragments as below,
function Glossary(props) {
    return (
        <dl>
            {props.items.map((item) => (
                // Without the `key`, React will fire a key warning
                <React.Fragment key={item.id}>
                    <dt>{item.term}</dt>
                    <dd>{item.description}</dd>
                </React.Fragment>
            ))}
        </dl>
    );
}
Note: key is the only attribute that can be passed to Fragment. In the future, there might be a support for additional attributes, such as event handlers.

Front: What is code-splitting?
Back: Code-Splitting is a feature supported by bundlers like Webpack and Browserify which can create multiple bundles that can be dynamically loaded at runtime. The react project supports code splitting via dynamic import() feature.
For example, in the below code snippets, it will make moduleA.js and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
moduleA.js
const moduleA = 'Hello';
export { moduleA };
App.js
export default function App {
  function handleClick() {
    import("./moduleA")
      .then(({ moduleA }) => {
        // Use moduleA
      })
      .catch((err) => {
        // Handle failure
      });
  };
 return (
   <div>
     <button onClick={this.handleClick}>Load</button>
   </div>
 );
}
See Class
import React, { Component } from 'react';
class App extends Component {
    handleClick = () => {
        import('./moduleA')
            .then(({ moduleA }) => {
                // Use moduleA
            })
            .catch((err) => {
                // Handle failure
            });
    };
    render() {
        return (
            <div>
                <button onClick={this.handleClick}>Load</button>
            </div>
        );
    }
}
export default App;

Front: What is the browser support for react applications?
Back: React supports all popular browsers, including Internet Explorer 9 and above, although some polyfills are required for older browsers such as IE 9 and IE 10. If you use es5-shim and es5-sham polyfill then it even support old browsers that doesn't support ES5 methods.

Front: What is the purpose of displayName class property?
Back: The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component.
For example, To ease debugging, choose a display name that communicates that it’s the result of a withSubscription HOC.
function withSubscription(WrappedComponent) {
    class WithSubscription extends React.Component {
        /* ... */
    }
    WithSubscription.displayName = `WithSubscription(${getDisplayName(
        WrappedComponent,
    )})`;
    return WithSubscription;
}
function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

Front: What are default props?
Back: The defaultProps can be defined as a property on the component to set the default values for the props. These default props are used when props not supplied(i.e., undefined props), but not for null or 0 as props. That means, If you provide null value then it remains null value. It's the same behavior with 0 as well.
For example, let us create color default prop for the button component,
function MyButton {
  // ...
}
MyButton.defaultProps = {
  color: "red",
};
If props.color is not provided then it will set the default value to 'red'. i.e, Whenever you try to access the color prop it uses the default value
function MyButton() {
    return <MyButton />; // props.color will contain red value
}

Front: What is the benefit of component stack trace from error boundary?
Back: Apart from error messages and javascript stack, React16 will display the component stack trace with file names and line numbers using error boundary concept.
For example, BuggyCounter component displays the component stack trace as below,

Front: What is the proper placement for error boundaries?
Back: The granularity of error boundaries usage is up to the developer based on project needs. You can follow either of these approaches,
1. You can wrap top-level route components to display a generic error message for the entire application.
2. You can also wrap individual components in an error boundary to protect them from crashing the rest of the application.

Front: What is the behavior of uncaught errors in react 16?
Back: In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it. For example, it is worse for a payments app to display a wrong amount than to render nothing.

Front: In which scenarios do error boundaries not catch errors?
Back: Below are the cases in which error boundaries don't work,
1. Inside Event handlers
2. Asynchronous code using setTimeout or requestAnimationFrame callbacks
3. During Server side rendering
4. When errors thrown in the error boundary code itself

Front: Can you describe about componentDidCatch lifecycle method signature?
Back: The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters,
1. error: - The error object which was thrown
2. info: - An object with a componentStack key contains the information about which component threw the error.
The method structure would be as follows
componentDidCatch(error, info);

Front: What are the benefits of React Router V4?
Back: Below are the main benefits of React Router V4 module,
1. In React Router v4(version 4), the API is completely about components. A router can be visualized as a single component(<BrowserRouter>) which wraps specific child router components(<Route>).
2. You don't need to manually set history. The router module will take care history by wrapping routes with <BrowserRouter> component.
3. The application size is reduced by adding only the specific router module(Web, core, or native)

Front: What are the differences between Flux and Redux?
Back: Below are the major differences between Flux and Redux
Flux | Redux
State is mutable | State is immutable
The Store contains both state and change logic | The Store and change logic are separate
There are multiple stores exist | There is only one store exist
All the stores are disconnected and flat | Single store with hierarchical reducers
It has a singleton dispatcher | There is no concept of dispatcher
React components subscribe to the store | Container components uses connect function

Front: How to ensure hooks followed the rules in your project?
Back: React team released an ESLint plugin called eslint-plugin-react-hooks that enforces Hook's two rules. It is part of Hooks API. You can add this plugin to your project using the below command,
npm install eslint-plugin-react-hooks --save-dev
And apply the below config in your ESLint config file,
// Your ESLint configuration
{
  "plugins": [
    // ...
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error"
  }
}
The recommended eslint-config-react-app preset already includes the hooks rules of this plugin.
For example, the linter enforce proper naming convention for hooks. If you rename your custom hooks which as prefix "use" to something else then linter won't allow you to call built-in hooks such as useState, useEffect etc inside of your custom hook anymore.
Note: This plugin is intended to use in Create React App by default.

Front: What rules need to be followed for hooks?
Back: You need to follow two rules in order to use hooks,
1. Call Hooks only at the top level of your react functions: You should always use hooks at the top level of react function before any early returns. i.e, You shouldn’t call Hooks inside loops, conditions, or nested functions. This will ensure that Hooks are called in the same order each time a component renders and it preserves the state of Hooks between multiple re-renders due to useState and useEffect calls.
2. Call Hooks from React Functions only: You shouldn’t call Hooks from regular JavaScript functions or class components. Instead, you should call them from either function components or custom hooks.

Front: What are hooks?
Back: Hooks is a special JavaScript function that allows you use state and other React features without writing a class. This pattern has been introduced as a new feature in React 16.8 and helped to isolate the stateful logic from the components.
Let's see an example of useState hook:
import { useState } from 'react';
function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);
    return (
        <>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>Click me</button>
        </>
    );
}
Note: Hooks can be used inside an existing function component without rewriting the component.

Front: How do you render Array, Strings and Numbers in React 16 Version?
Back: Arrays: Unlike older releases, you don't need to make sure render method return a single element in React16. You are able to return multiple sibling elements without a wrapping element by returning an array.
For example, let us take the below list of developers,
const ReactJSDevs = () => {
    return [
        <li key='1'>John</li>,
        <li key='2'>Jackie</li>,
        <li key='3'>Jordan</li>,
    ];
};
You can also merge this array of items in another array component.
const JSDevs = () => {
    return (
        <ul>
            <li>Brad</li>
            <li>Brodge</li>
            <ReactJSDevs />
            <li>Brandon</li>
        </ul>
    );
};
Strings and Numbers: You can also return string and number type from the render method.
render() {
 return 'Welcome to ReactJS questions';
}
// Number
render() {
 return 2018;
}

Front: How to prevent unnecessary updates using setState?
Back: You can compare the current value of the state with an existing state value and decide whether to rerender the page or not. If the values are the same then you need to return null to stop re-rendering otherwise return the latest state value.
For example, the user profile information is conditionally rendered as follows,
getUserProfile = (user) => {
    const latestAddress = user.address;
    this.setState((state) => {
        if (state.address === latestAddress) {
            return null;
        } else {
            return { title: latestAddress };
        }
    });
};

Front: What is React lazy function?
Back: The React.lazy function lets you render a dynamic import as a regular component. It will automatically load the bundle containing the OtherComponent when the component gets rendered. This must return a Promise which resolves to a module with a default export containing a React component.
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
    return (
        <div>
            <OtherComponent />
        </div>
    );
}
Note:
React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we still recommend React Loadable.

Front: What is React memo function?
Back: Class components can be restricted from re-rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.
const MyComponent = React.memo(function MyComponent(props) {
    /* only rerenders if props change */
});

Front: What is the purpose of registerServiceWorker in React?
Back: React creates a service worker for you without any configuration by default. The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that's what you should know about service worker for now. It's all about adding offline capabilities to your site.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

Front: Do I need to keep all my state into Redux? Should I ever use react internal state?
Back: It is up to the developer's decision, i.e., it is developer's job to determine what kinds of state make up your application, and where each piece of state should live. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.
Below are the rules of thumb to determine what kind of data should be put into Redux
1. Do other parts of the application care about this data?
2. Do you need to be able to create further derived data based on this original data?
3. Is the same data being used to drive multiple components?
4. Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
5. Do you want to cache the data (i.e, use what's in state if it's already there instead of re-requesting it)?

Front: How to pass numbers to React component?
Back: We can pass numbers as props to React component using curly braces {} where as strings in double quotes "" or single quotes ''
import React from 'react';
const ChildComponent = ({ name, age }) => {
    return (
        <>
            My Name is {name} and Age is {age}
        </>
    );
};
const ParentComponent = () => {
    return (
        <>
            <ChildComponent name='Chetan' age={30} />
        </>
    );
};
export default ParentComponent;

Front: What is render hijacking in react?
Back: The concept of render hijacking is the ability to control what a component will output from another component. It means that you decorate your component by wrapping it into a Higher-Order component. By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enable hijacking, but by using HOC you make your component behave differently.

Front: Can I import an SVG file as react component?
Back: You can import SVG directly as component instead of loading it as a file. This feature is available with react-scripts@2.0.0 and higher.
import { ReactComponent as Logo } from './logo.svg';
const App = () => (
    <div>
        {/* Logo is an actual react component */}
        <Logo />
    </div>
);
Note: Don't forget about the curly braces in the import.

Front: How React PropTypes allow different types for one prop?
Back: You can use oneOfType() method of PropTypes.
For example, the height property can be defined with either string or number type as below:
Component.propTypes = {
    size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};

Front: How Redux Form initialValues get updated from state?
Back: You need to add enableReinitialize : true setting.
const InitializeFromStateForm = reduxForm({
    form: 'initializeFromState',
    enableReinitialize: true,
})(UserEdit);
If your initialValues prop gets updated, your form will update too.

Front: Do you need to have a particular build tool to use Redux?
Back: Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel. You should be able to use it regardless of your JavaScript build process. Redux also offers a UMD build that can be used directly without any build process at all.

Front: Can Redux only be used with React?
Back: Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.

Front: # Give an example of Reselect usage?
Back: Let's take calculations and different amounts of a shipment order with the simplified usage of Reselect:
import { createSelector } from 'reselect';
const shopItemsSelector = (state) => state.shop.items;
const taxPercentSelector = (state) => state.shop.taxPercent;
const subtotalSelector = createSelector(shopItemsSelector, (items) =>
    items.reduce((acc, item) => acc + item.value, 0),
);
const taxSelector = createSelector(
    subtotalSelector,
    taxPercentSelector,
    (subtotal, taxPercent) => subtotal * (taxPercent / 100),
);
export const totalSelector = createSelector(
    subtotalSelector,
    taxSelector,
    (subtotal, tax) => ({ total: subtotal + tax }),
);
let exampleState = {
    shop: {
        taxPercent: 8,
        items: [
            { name: 'apple', value: 1.2 },
            { name: 'orange', value: 0.95 },
        ],
    },
};
console.log(subtotalSelector(exampleState)); // 2.15
console.log(taxSelector(exampleState)); // 0.172
console.log(totalSelector(exampleState)); // { total: 2.322 }

Front: What are the main features of Reselect library?
Back: Let's see the main features of Reselect library,
1. Selectors can compute derived data, allowing Redux to store the minimal possible state.
2. Selectors are efficient. A selector is not recomputed unless one of its arguments changes.
3. Selectors are composable. They can be used as input to other selectors.