FrontendDeveloper.in

React Interview Questions

  • Question 301

    Can useRef be used to store previous values?

    Yes, useRef is a common pattern when you want to compare current and previous props or state without causing re-renders.

    Example: Storing previous state value

    import { useEffect, useRef, useState } from 'react';
    
    function PreviousValueExample() {
    const [count, setCount] = useState(0);
    const prevCountRef = useRef();
    
    useEffect(() => {
    prevCountRef.current = count;
    }, [count]);
    
    const prevCount = prevCountRef.current;
    
    return (
    <button onClick={() => setCount(c => c + 1)}>Increment</button>
    );
    }
    
  • Question 302

    Is it possible to access a ref in the render method?

    Yes, you can access a ref in the render method, but what you get from it depends on how you're using the ref and when in the component lifecycle you're rendering.

    For example, when using ref to access a DOM node (e.g., divRef.current), it's not immediately available on the first render.

    const divRef = useRef(null);
    
    console.log(divRef.current); // ❌ null on initial render
    return <div ref={divRef}>Hello</div>;
    
  • Question 303

    What are the common usecases of useRef hook?

    Some of the common cases are:

    • Automatically focus an input when a component mounts.
    • Scroll to a specific element.
    • Measure element dimensions (offsetWidth, clientHeight).
    • Control video/audio playback.
    • Integrate with non-React libraries (like D3 or jQuery).
  • Question 304

    What is useImperativeHandle Hook? Give an example.

    useImperativeHandle is a React Hook that allows a child component to expose custom functions or properties to its parent component, when using ref. It is typically used with forwardRef and is very useful in cases like modals, dialogs, custom inputs, etc., where the parent needs to control behavior imperatively (e.g., open, close, reset).

    Example: Dialog component

    import React, {
    useRef,
    useState,
    useImperativeHandle,
    forwardRef,
    } from 'react';
    import './Dialog.css';
    
    const Dialog = forwardRef((props, ref) => {
    const [isOpen, setIsOpen] = useState(false);
    const [formData, setFormData] = useState('');
    
    useImperativeHandle(ref, () => ({
    open: () => setIsOpen(true),
    close: () => setIsOpen(false),
    reset: () => setFormData(''),
    }));
    
    if (!isOpen) return null;
    
    return (
    <h2>Dialog</h2>
    <input
    type="text"
    value={formData}
    placeholder="Type something..."
    onChange={(e) => setFormData(e.target.value)}
    />
          
    
    <button onClick={() => setIsOpen(false)}>Close</button>
    );
    });
    
    function Parent() {
    const dialogRef = useRef();
    
    return (
    <h1>useImperativeHandle Dialog Example</h1>
    <button onClick={() => dialogRef.current.open()}>Open Dialog</button>
    <button onClick={() => dialogRef.current.reset()}>Reset Dialog</button>
    <button onClick={() => dialogRef.current.close()}>Close Dialog</button>
    
    <Dialog ref={dialogRef} />
    );
    }
    
    export default Parent;
    
  • Question 305

    When should you use useImperativeHandle?

    The useImperativeHandler hook will be used in below cases:

    • You want to expose imperative methods from a child component
    • Custom input controls exposing focus, clear, or validate methods
    • Modal components exposing open() and close() methods
    • Scroll containers exposing scrollToTop() or scrollToBottom() methods
    • You want to hide internal implementation but provide controlled external access.
    • You're building reusable component libraries (e.g., inputs, modals, form controls).
  • Question 307

    How is useMemo different from useCallback?

    The following table compares both useMemo and useCallback:

    FeatureuseMemouseCallback
    PurposeMemoizes the result of a computationMemoizes a function reference
    ReturnsA value (e.g., result of a function)A function
    UsageuseMemo(() => computeValue(), [deps])useCallback(() => doSomething(), [deps])
    Primary Use CaseAvoid expensive recalculationsPrevent unnecessary re-creations of functions
    Common ScenarioFiltering, sorting, calculating derived dataPassing callbacks to child components
    When It's UsefulWhen the value is expensive to computeWhen referential equality matters (e.g., props)
    Recomputed WhenDependencies changeDependencies change
    Returned Value TypeAny (number, object, array, etc.)Always a function
    OverheadSlight (evaluates a function and caches result)Slight (caches a function reference)
  • Question 308

    Does useMemo prevent re-rendering of child components?

    The useMemo hook does not directly prevent re-rendering of child components. Its main purpose is to memoize the result of an expensive computation so that it doesn’t get recalculated unless its dependencies change. While this can improve performance, it doesn’t inherently control whether a child component re-renders.

    However, useMemo can help prevent re-renders when the memoized value is passed as a prop to a child component that is wrapped in React.memo. In that case, if the memoized value doesn’t change between renders (i.e., it has the same reference), React.memo can skip re-rendering the child. So, while useMemo doesn’t stop renders on its own, it works in combination with tools like React.memo to optimize rendering behavior.

  • Question 309

    What is `useCallback` and why is it used?

    The useCallback is a React Hook used to memoize function definitions between renders. It returns the same function reference unless its dependencies change. This is especially useful when passing callbacks to optimized child components (e.g. those wrapped in React.memo) to prevent unnecessary re-renders.

    Example:

    const handleClick = useCallback(() => {
    console.log('Button clicked');
    }, []);
    

    Without useCallback, a new function is created on every render, potentially causing child components to re-render unnecessarily.

  • Question 310

    What are Custom React Hooks, and How Can You Develop One?

    Custom Hooks in React are JavaScript functions that allow you to extract and reuse component logic using React’s built-in Hooks like useState, useEffect, etc.

    They start with the word "use" and let you encapsulate logic that multiple components might share—such as fetching data, handling forms, or managing timers—without repeating code.

    Let's explain the custom hook usage with useFetchData example. The useFetchData custom Hook is a reusable function in React that simplifies the process of fetching data from an API. It encapsulates common logic such as initiating the fetch request, managing loading and error states, and storing the fetched data. By using built-in Hooks like useState and useEffect, useFetchData provides a clean interface that returns the data, loading, and error values, which can be directly used in components.

    import { useState, useEffect } from 'react';
    
    function useFetchData(url) {
    const [data, setData] = useState(null);     // Holds the response
    const [loading, setLoading] = useState(true); // Loading state
    const [error, setError] = useState(null);     // Error state
    
    useEffect(() => {
    let isMounted = true; // Prevent setting state on unmounted component
    setLoading(true);
    
    fetch(url)
    .then((response) => {
    if (!response.ok) throw new Error('Network response was not ok');
    return response.json();
    })
    .then((json) => {
    if (isMounted) {
    setData(json);
    setLoading(false);
    }
    })
    .catch((err) => {
    if (isMounted) {
    setError(err.message);
    setLoading(false);
    }
    });
    
    return () => {
    isMounted = false; // Clean-up function to avoid memory leaks
    };
    }, [url]);
    
    return { data, loading, error };
    }
    

    The above custom hook can be used to retrieve users data for AuthorList, ReviewerList components.

    Example: AuthorList component

    function AuthorList() {
    const { data, loading, error } = useFetchData('https://api.example.com/authors');
    
    if (loading) return <p>Loading authors...</p>;
    if (error) return <p>Error: {error}</p>;
    
    return (
    <ul>
    {data.map((author) => (
    <li key={author.id}>{author.name}</li>
    ))}
    </ul>
    );
    }
    

    Some of the benefits of custom hooks are:

    • Promotes code reuse
    • Keeps components clean and focused
    • Makes complex logic easier to test and maintain
  • Question 312

    1. **Fiber Tree Structure**

    Each component in your app is represented by a Fiber node in a tree structure. A Fiber node contains:

    • Component type
    • Props & state
    • Pointers to parent, child, and sibling nodes
    • Effect tags to track changes (e.g., update, placement)
    • This forms the Fiber Tree, a data structure React uses instead of the traditional call stack.
  • Question 313

    2. **Two Phases of Rendering**

    A. Render Phase (work-in-progress)

    • React builds a work-in-progress Fiber tree.
    • It walks through each component (begin phase), calculates what needs to change, and collects side effects (complete phase).
    • This phase is interruptible—React can pause it and resume later.

    B. Commit Phase

    • React applies changes to the Real DOM.
    • Runs lifecycle methods (e.g., componentDidMount, useEffect).
    • This phase is non-interruptible but fast.
  • Question 314

    3. **Work Units and Scheduling**

    • React breaks rendering into units of work (small tasks).
    • These units are scheduled based on priority using the React Scheduler.
    • If time runs out (e.g., user starts typing), React can pause and yield control back to the browser.
  • Question 315

    4. **Double Buffering with Two Trees**

    • React maintains two trees:
    • Current Tree – what's visible on the screen.
    • Work-In-Progress Tree – the next version being built in memory.
    • Only after the new tree is fully ready, React commits it, making it the new current tree.
Get LinkedIn Premium at Rs 399