Background

React is a JavaScript library to build user interfaces. It is used to build single-page applications and allows to create reusable UI components. React JS is also known as React or React.js.

This article is being read specifically for purposes like:

Questions

  1. Which of the following option is NOT a React Hook?

  2. What is the benefit of useLayoutEffect over useEffect?

  3. What replaces Redirect in React Router v6?

  4. What is the execution of useEffect(() => {}, [])?

  5. What is real use-case for useReducer over useState?

  6. What is use of jest.fn()?

  7. When to use useImperativeHandle?

  8. What is the role of Provider in Context API?

  9. Which of the following testing method checks if a component is rendered?

  10. In which scenario to use React.PureComponent?

  11. How to prevent re-renders of child components in React?

  12. What does the useMemo hook do in React?

  13. How to improve re-render performance of a list component?

  14. Which hook helps to prevent unnecessary re-creations of functions on re-renders?

  15. What does createAsyncThunk do in Redux Toolkit?

  16. Which of the following hook is used for animation frame updates?

  17. Which of the following should an Error Boundary component implement?

  18. What is side effect in React?

  19. What is the main benefit of dynamic imports in React?

  20. When to use useTransition?

  21. Which of the option is NOT allowed inside a custom hook?

  22. Which method helps in pre-fetching routes in React Router v6?

  23. Which method logs errors in error boundaries?

  24. Which feature supports concurrent rendering in React?

  25. What is required for SSR in React?

Answers

1. Which of the following option is NOT a React Hook?

Correct Answer:

Explanation:

useFetch is not a React Hook. It is a custom hook. Developers create it to encapsulate data-fetching logic. It does not exist in React’s core API.

Why other options are correct?

2. What is the benefit of useLayoutEffect over useEffect?

Correct Answer:

Explanation:

useLayoutEffect runs synchronously after DOM mutations and before browser paints screen. It is used to read layout values such as size, position, etc. It makes DOM changes before user sees anything and prevents flickering like visual glitches.

Generally useLayoutEffect is used to measure DOM elements using getBoundingClientRect, to adjust layout immediately, and to prevent UI flicker.

useEffect is used by default while useLayoutEffect is used only when to block painting to adjust layout.

Why other options are incorrect?

3. What replaces Redirect in React Router v6?

Correct Answer:

Explanation:

In React Router v6, old Redirect component of v5 was removed and replaced with <Navigate />.

<Navigate /> is used programmatically to redirect users to another route. It is simplified and modernized.

JSX

import { Navigate } from "react-router-dom";
function ProtectedRoute({ isAuth }) {
     return isAuth ? <Dashboard /> : <Navigate to="/login" replace />;
}

Here, <Navigate /> replaces Redirect for handling redirects.

Why other options are incorrect?

4. What is the execution of useEffect(() => {}, [])?

Correct Answer:

Explanation:

useEffect(() => {}, []) has empty dependency array. Hence, it runs effect once, after component mounted. It does not rerun on re-renders or state/prop changes.

It is generally used to call API on component load, to setup event listener, to initialize or subscribe logic.

JavaScript

useEffect(() => {
     // side effect code
}, []);

Why other options are incorrect?

5. What is real use-case for useReducer over useState?

Correct Answer:

Explanation:

useReducer is used for complex state transitions. It is used to manage next state which depends on previous state. It allows to manage multiple related state values. Generally, state updates follow actions such as add, remove, reset item.

It is best option to manage component’s complex state logic, to update state depends on previous state, or to handle multiple action types. useReducer is lightweight alternative to Redux.

JavaScript

const reducer = (state, action) => {
     switch (action.type) {
          case "increment":
               return { count: state.count + 1 };
          case "decrement":
               return { count: state.count - 1 };
          default:
               return state;
     }
};
const [state, dispatch] = useReducer(reducer, { count: 0 });

Why other options are incorrect?

6. What is use of jest.fn()?

Correct Answer:

Explanation:

jest.fn() is a utility provided by Jest. It is used to create mock function. Mock function permits to track how function called i.e. arguments/parameters, return values, count call, etc. It replaces actual implementations in tests.

jest.fn() is used for mocking callbacks/dependencies and to verify interaction in unit tests.

JavaScript

const mockFn = jest.fn();
mockFn(1, 2);
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith(1, 2);

Why other options are incorrect?

7. When to use useImperativeHandle?

Correct Answer:

Explanation:

useImperativeHandle is used to customize ref handling. It allows to control methods/values exposed to parent component through ref. It is a React Hook and mostly used with forwardRef to expose specific imperative API. It allows to define custom interface for ref.

useImperativeHandle is used to expose only certain methods such as focus, reset, etc. It allows to hide internal implementation details. Using it parent can imperative control over child component.

JavaScript

import { forwardRef, useImperativeHandle, useRef } from "react";

     const Input = forwardRef((props, ref) => {
     const inputRef = useRef();

     useImperativeHandle(ref, () => ({
          focus: () => inputRef.current.focus(),
     }));

     return <input ref={inputRef} />;
});

Here, parent can call ref.current.focus() method without accessing DOM directly.

Why other options are incorrect?

8. What is the role of Provider in Context API?

Correct Answer:

Explanation:

The role of Provider in Context API is to provide values to consumers. It is used to provide/supply data to all child components which consumes that context. There is no need to pass props manually at every level. It is used to define what data is shared and where it is available in component tree.

JSX

const ThemeContext = React.createContext();

function App() {
     return (
          <ThemeContext.Provider value="dark">
                                                       <Toolbar />
                                   </ThemeContext.Provider>
     );
}

function Toolbar() {

     const theme = React.useContext(ThemeContext);

     return <div>{theme}</div>;
}

Here, it outputs dark as <Toolbar/> component can access using useContext(MyContext) or Context.Consumer.

Why other options are incorrect?

9. Which of the following testing method checks if a component is rendered?

Correct Answer:

Explanation:

screen.getByText() testing method is used to check whether component, part of it, or specific text within it is rendered in DOM or not.

It synchronously queries DOM and throws error if text not found. It is used to confirm the rendering.

JavaScript

render(<MyComponent />);

expect(screen.getByText("Hello World")).toBeInTheDocument();

Here, If text is not present then getByText throws error and causing test to fail.

Why other options are incorrect?

10. In which scenario to use React.PureComponent?

Correct Answer:

Explanation:

React.PureComponent is used with class based components to optimize rendering performance. It allows to implement shallow comparison of props and states to optimize performance. It automatically implements shouldComponentUpdate with shallow comparison to avoid unnecessary renders.

Based on shallow comparison, component will no re-render if props or state not changed. It helps to avoid unnecessary re-rendering while component receives same data repeatedly.

JavaScript

class MyComponent extends React.PureComponent {
     render() {
          return <div>{this.props.value}</div>;
     }
}

Here, MyComponent only re-render if value changes.

JavaScript - Modern equivalent - For functional components, use:

const MyComponent = React.memo(function MyComponent(props) {
     return <div>{props.value}</div>;
});

Why other options are incorrect?

11. How to prevent re-renders of child components in React?

Correct Answer:

Explanation:

React.memo is recommended solution for functional components to optimize rendering performance. It is used to prevent unnecessary re-renders if child components through component memoizing.

React.memo memoizes component and then re-renders it only if it’s props change using shallow comparison. If parent re-renders but child will not re-render, if child props are same.

Functional component uses React.memo and class component uses React.PureComponent to optimize child components and avoid unnecessary re-renders while props remain unchanged.

JSX

const Child = React.memo(({ value }) => {
     console.log("Child rendered");
     return <div>{value}</div>;
});

function Parent() {
     const [count, setCount] = React.useState(0);
     return (
          <>
                                                       <Child value="Hello" />
                                                       <button onClick={() => setCount(count + 1)}>+</button>
                                   </>
     );
}

Here, clicking button will not re-render Child, because Child props is not change.

Why other options are incorrect?

12. What does the useMemo hook do in React?

Correct Answer:

Explanation:

In React, useMemo hook is used to memoize (cache) computation result and it is recomputed only when it’s dependency changes. It returns memoized value.

It is used for expensive calculation and value is derived from props or state. It allows to avoid unnecessary recalculations on re-renders.

JSX

const expensiveValue = useMemo(() => {

     return computeExpensiveValue(a, b);

}, [a, b]);

``

Here, computed result is cached and reuses previously computed value unless a or b not changes. It optimize performance by avoiding unnecessary recalculation during re-render.

Why other options are incorrect?

13. How to improve re-render performance of a list component?

Correct Answer:

Explanation:

Wrap in React.memo improves re-render performance of list component. Wrapping list items in to React.memo improves performance by preventing unnecessary re-rendering. List component re-renders only if props changed, using shallow comparison technique.

It is useful, where parent component re-renders frequently or where list items don’t change frequently.

Best practice to improve list performance:

JSX

const ListItem = React.memo(({ item }) => {
     return <li>{item.name}</li>;
});

function List({ items }) {
     return (
          <ul>
                                                       {items.map(item => (
                                                                 <ListItem key={item.id} item={item} />
                                                       ))}
                                   </ul>
     );
}

Here, ListItem only re-renders if item’s prop changes.

Why other options are incorrect?

14. Which hook helps to prevent unnecessary re-creations of functions on re-renders?

Correct Answer:

Explanation:

useCallback hook helps to prevent unnecessary re-creations of functions on re-renders. It is used to memoize a function. Hence, React does not recreate it on every re-render unless its dependencies change.

During component re-renders any function declared inside it is recreated by default and this cause performance related issues.

useCallback returns memoized version of callback function which only changes/calls if its dependencies change.

JSX - Without useCallback

const handleClick = useCallback(() => {
     console.log("Clicked");
}, []);

Here, handleClick recreated on every render.

JSX - With useCallback

const Button = React.memo(({ onClick }) => {
     return <button onClick={onClick}>Click</button>;
});

function Parent() {
     const [count, setCount] = useState(0);

     const handleClick = useCallback(() => {
          setCount(c => c + 1);
     }, []);

     return <Button onClick={handleClick} />;
}

Here, Button won’t re-render unnecessarily because onClick function reference stays same as it is.

This is useful to:

Quick rule of thumb is useCallback as Memoize functions as useMemo as Memoize computed values

Why other options are incorrect?

15. What does createAsyncThunk do in Redux Toolkit?

Correct Answer:

Explanation:

In Redux Toolkit, createAsyncThunk is used to handle asynchronous logic like API calls inside the Redux actions. It automatically dispatches pending action while async process starts. It automatically generates pending, fulfilled or rejected threes action types for async process.

Advantages:

JavaScript

export const fetchUsers = createAsyncThunk(
     "users/fetchUsers",
     async () => {
          const response = await fetch("/api/users");
          return response.json();
     }
);

JavaScript

extraReducers: (builder) => {
     builder
     .addCase(fetchUsers.pending, (state) => {
          state.status = "loading";
     })
     .addCase(fetchUsers.fulfilled, (state, action) => {
          state.users = action.payload;
     })
     .addCase(fetchUsers.rejected, (state) => {
          state.status = "failed";
     });
};

Why other options are incorrect?

16. Which of the following hook is used for animation frame updates?

Correct Answer:

Explanation:

useLayoutEffect hook is used for animation frame updates. It runs synchronously after DOM mutations and before browser repaints which makes it ideal for measuring layout. It helps to avoid flicker and ensures smoother animations.

useLayoutEffect is used for animation frame updates and layout-sensitive changes. Especially, when timing with browser’s paint cycle matters.

JSX

useLayoutEffect(() => {

     let frameId;

     const animate = () => {
          // update animation state
          frameId = requestAnimationFrame(animate);
     };

     frameId = requestAnimationFrame(animate);

     return () => cancelAnimationFrame(frameId);

}, []);

Rule of thumb:

Why other options are incorrect?

17. Which of the following should an Error Boundary component implement?

Correct Answer:

Explanation:

In React, an Error Boundary is a special class component. It is used to catch errors in its child component tree. Error Boundary class component catches JavaScript errors anywhere in its child component tree and prevents entire app from crashing.

It is implemented using two lifecycle methods:

JSX - Error Boundary

class ErrorBoundary extends React.Component {
     constructor(props) {
          super(props);
          this.state = { hasError: false };
     }
     static getDerivedStateFromError(error) {
          return { hasError: true };
     }
     componentDidCatch(error, errorInfo) {
          console.error(error, errorInfo);
     }
     render() {
          if (this.state.hasError) {
               return <h1>Something went wrong.</h1>;
          }
          return this.props.children;
     }
}

Key takeaway: An Error Boundary must implement getDerivedStateFromError and componentDidCatch to catch and handle rendering errors in React applications.

Why other options are incorrect?

18. What is side effect in React?

Correct Answer:

Explanation:

In React, side effect is anything that affects something outside scope of function or interacts with outside world. In other words, it is any operation that interacts with something outside component’s render scope or has effects beyond returning JSX.

These actions are handled inside useEffect or useLayoutEffect using useEffect or related hooks.

Real life use cases are:

JSX

useEffect(() => {
     fetch("/api/users")
     .then(res => res.json())
     .then(data => setUsers(data));
}, []);

Why other options are incorrect?

19. What is the main benefit of dynamic imports in React?

Correct Answer:

Explanation:

In React, dynamic imports allows to load code only when it’s needed instead of bundling everything upfront. Key benefit is lazy loading which loads code only when it’s needed instead of bundling everything upfront. Dynamic imports commonly implemented with React.lazy() and split code to load components on demand.

Advantages:

JSX

const Dashboard = React.lazy(() => import("./Dashboard"));
function App() {
     return (
          <Suspense fallback={<div>Loading...</div>}>
                                             <Dashboard />
                                   </Suspense>
     );
}

Here, Dashboard loads only when rendered that reduces initial bundle size.

JavaScript

const LazyComponent = React.lazy(() => import('./MyComponent'));

Why other options are incorrect?

20. When to use useTransition?

Correct Answer:

Explanation:

In React, useTransition is a hook which marks certain updates as non-urgent. Hence, React can keep UI responsive while performing expensive state updates in background.

It helps to avoid UI blocking during:

JavaScript

const [isPending, startTransition] = useTransition();
startTransition(() => {
     setFilteredItems(expensiveFilter(data));
});

Here, startTransition wraps non-urgent updates. isPending shows loading indicators during transition runs.

Why other options are incorrect?

21. Which of the option is NOT allowed inside a custom hook?

Correct Answer:

Explanation:

In React, custom hook can not return or contain JSX. It is a pure logic reuse function and not UI components. Custom hook is a JavaScript function which uses one ore more hooks to share the logic.

useEffect, useState, useContext, and other hooks are allwed to use inside a custom hook. But JSX is not allowed JSX is for UI rendering and hooks can not render anything. Key purpose of custom hooks is to encapsulate reusable logic such as return value, functions, or objects instead of UI. They can not render anything or JSX.

JSX is returned only from components instead of hooks.

JavaScript - valid custom hook

function useCounter() {
     const [count, setCount] = useState(0);
     const increment = () => setCount(c => c + 1);

     return { count, increment };
}

JavaScript - invalid hook usage

function useInvalidHook() {
     return <div>Hello</div>; // not JSX in a hook
}

Why other options are correct?

22. Which method helps in pre-fetching routes in React Router v6?

Correct Answer:

Explanation:

In React Router v6, loader() method helps in pre-fetching routes. Data API introduced loader() function which executes before route rendering. Hence, it can be used for pre-fetching route data which allows components to receive data immediately as and when they mount.

loader() method is used to pre-fetch route data before navigation completes. It allows data to load parallel with route matching that gives smoother and faster user experience. In another words, it is a mechanism that enables route data pre-fetching before rendering.

JavaScript

import { createBrowserRouter } from "react-router-dom";
const router = createBrowserRouter([
{
     path: "/users",
     element: <Users />,
     loader: async () => {
          return fetch("/api/users");
     },
},
]);

Here, React Router runs loader() before navigating to users which ensures data is ready while component renders.

Advantages:

Why other options are incorrect?

23. Which method logs errors in error boundaries?

Correct Answer:

Explanation:

In React, componentDidCatch method logs errors in error boundaries. componentDidCatch(error, errorInfo) is lifecycle method logs errors that occur in child components.

It is typically used to:

JSX

class ErrorBoundary extends React.Component {
     componentDidCatch(error, errorInfo) {
          console.error("Error caught:", error, errorInfo);
     }
     render() {
          return this.props.children;
     }
}

Why other options are incorrect?

24. Which feature supports concurrent rendering in React?

Correct Answer:

Explanation:

In React, useTransition feature supports concurrent rendering. It keeps UI responsive without blocking by making certain state updates as non-urgent (low-priority).

Advantages:

JavaScript

const [isPending, startTransition] = useTransition();
startTransition(() => {
     setResults(expensiveSearch(query));
});

Here, React can pause or interrupt result rendering if higher-priority update occurs.

Why other options are incorrect?

25. What is required for SSR in React?

Correct Answer:

Explanation:

In React, Node.js server is required to Server-Side Rendering (SSR). It is server environment capable to renders React components on server side and sending resulting HTML to browser.

React renders the components on the server using Node.js and server sends fully rendered HTML to the client. There are several tools such as Next.js, Remix, Custom Express, etc. uses Node.js.

Why other options are incorrect?

Summary

In this article, each questions is having four options. After each question, correct answer is given along with detailed explanation and with code examples. Hence, it gives actual idea about the concept or feature when to use and how to use. Now, you will be able to crack advanced level certifications, challenges, or interviews of React JS.