FrontendDeveloper.in

React Interview Questions

  • Question 241

    How is the new JSX transform different from old transform??

    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.

  • Question 242

    What are React Server components?

    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.

  • Question 243

    What is prop drilling?

    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.

  • Question 244

    What is the difference between useState and useRef hook?

    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 and tracking values.
  • Question 245

    What is a wrapper component?

    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 (
    <Message {...props} />
    );
    };
    

    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 (
    <h3>{title}</h3>
    <Message {...props} />
    );
    };
    

    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.

  • Question 246

    What are the differences between useEffect and useLayoutEffect hooks?

    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.

  • Question 247

    What are the differences between Functional and Class Components?

    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 (
    <h1>Hello, I'm a function component</h1>
    );
    }
    

    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 (
    <h1>{message} </h1>
    <button onClick={updateMessage}>Click me!!</button>
    );
    }
    

    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 (
    <Child name="First child component" />
    <Child name="Second child component" />
    );
    }
    }
    

    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 (
    <Child name="First child component" />
    <Child name="Second child component" />
    );
    }
    
  • Question 248

    What is strict mode in React?

    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 (
    <Header />
    <StrictMode>
    <ComponentOne />
    <ComponentTwo />
    </StrictMode>
    <Header />
    );
    }
    

    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.

  • Question 249

    What is the benefit of strict mode?

    The <StrictMode> 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
  • Question 250

    Why does strict mode render twice in React?

    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
  • Question 251

    What are the rules of JSX?

    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.

    1. 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.
    2. 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.
  • Question 252

    What is the reason behind multiple JSX tags to be wrapped?

    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.

  • Question 253

    How do you prevent mutating array variables?

    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.
  • Question 254

    What are capture phase events?

    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.

    <button onClick={(e) => e.stopPropagation()} />
    <button onClick={(e) => e.stopPropagation()} />
    

    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.
  • Question 255

    How does React updates screen in an application?

    React updates UI in three steps,

    1. Triggering or initiating a render: The component is going to triggered for render in two ways.

    2. 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.

Get LinkedIn Premium at Rs 399