ReactJS Interview Questions


What is React

React is a UI library used to build dynamic web applications. It is an open source project developed by Jordan Walke at facebook in 2013. Here is an example of a basic react code

import React from 'react';

export default function App() {
    return <h1>Hello World!</h1>
}

What are the features of React?

Following are the features of React-

  1. JSX - JSX is a syntax extension to JavaScript. With JSX, you can write HTML inside JavaScript
  2. Virtual DOM - Virtual DOM is a copy of actual DOM. React uses it to efficiently perform DOM updates
  3. One-way data binding - It decides the flow of data and how React app is designed. React follows unidirectional data flow.
  4. Components - In React everything is seen as a component. A component is an independent/reusable building blocks that together forms UI.
  5. SSR(Server Side Rendering) - React supports SSR which renders HTML in server instead of regular client/browser side rendering. This significantly improves SEO.

What is JSX?

JSX or JavaScript XML is a syntax extension to JavaScript. This enables HTML code to be written inside JavaScript file/code block. It is a modern way of designing user interfaces. Browser uses transpiler like babel to convert JSX into browser compatible JavaScript code.

Below is an example of JSX:

// JavaScript function containing HTML code
export function App() {
    return (
        <>
            <h1>React App</h1>
            <p>This is an example of JSX</p>
        </>
    )
}

What is Virtual DOM?

Virtual DOM is a lightweight representation of Real DOM. It is stored in memory and kept in sync with Real DOM. React keep track of changes and update only required node objects in real dom. This improves performance significantly.

What is difference between Real DOM and Virtual DOM?

Real DOM Virtual DOM
Slower Update Faster Update
HTML nodes are updated directly HTML node are not updated directly
Updates entire node tree Updates only necessary node

Explain Reconciliation

The process of modifying the Real DOM with only necessary updates is known as Reconciliation. It is a process where React updates Virtual DOM and calculates the changes required using an algorithm called "Diffing Algorithm". Then, React makes changes in the Real DOM. This process significantly improves efficiency.

What is React Fiber?

React Fiber is a new Reconciliation Engine introduced in React 16. It is an ongoing re implementation of React's core algorithm. The main feature of React Fiber is Incremental Rendering.

What are Components?

Components are a piece of code that returns HTML/JSX. They are the independent code blocks that represent UI elements. Components can be reused and isolated.

How many type of Components are there in React?

There are two type of Components in React-

  1. Class Components - written as class and used render() method to return JSX
  2. Functional components - written as function and JSX is returned directly

Class Components

class App extends React.Component {
    render() {
        <h1>Class Component</h1>
    }
}

Functional Components

function App() {
    return <h1>Functional Component</h1>
}

Explain State

State is an object that holds the information about component and is accessible within component. The component re renders whenever state value changes. It is declared for Class and Functional components as follows-

Class Component

this.state = {
    name: 'Bruce'
}

Function Component

const [name, setName] = useState('Bruce');

useState is a hook which returns an array with variable and a function to set variable value.

How to update the state?

We can update the state using following ways-

  1. Class component
this.state = {
    name: 'John'
}
this.setState({
    name: 'Henry'
});
// name is updated to Henry
  1. Function component
const [name, setName] = useState('John');
setName('Henry'); // name is updated to Henry

Explain Props

Props(properties) are inputs passed as attributes to a component. It is passed from parent component to child component. Props are read-only objects which defines the behavior of a component.

E.g.

function Greet(props) {
    return <h1>Hello {props.name}</h1>
}

function App() {
    return <Greet name = "David" />
}

In class based components, props are access by this.props

Explain prop drilling

The passing of prop from one component to another component in a nested manner is known as prop drilling. It happens when a prop is passed through several component to reach the specific child component.

E.g.

function Comp4({name}) {
    return `Hi ${name}`
}
function Comp3({name}) {
    return <Comp4 name={name} />
}
function Comp2({name}) {
    return <Comp3 name={name} />
}
function Comp1() {
    return <Comp2 name="Tom" />
}

Here, name is passed all the way down to Comp4 through Comp2 and Comp3 which doesn't need the name prop.

Explain Component lifecycle

A Component lifecycle goes through the following phases-

  1. Mounting - The phase when component renders on DOM
  2. Updating - The phase when component updates (through state and props)
  3. Unmounting - The phase when component is unmounted from DOM

What are the lifecycle methods?

Following are the lifecycle methods in React-

  1. getDerivedStateFromProps - This method runs before render method is invoked
  2. componentDidMount - This method runs once the component is mounted on DOM
  3. shouldComponentUpdate - This method is used to decide if component will rerender. By default, it returns true. To prevent rerender, return false
  4. getSnapshotBeforeUpdate - This method runs before updates are made to DOM
  5. componentDidUpdate - This method runs after component is updated due to state/props changes
  6. componentWillUnmount - This method runs before component is about to unmount. It can be used to perform any cleanup operation before component unmounts

How to render a list in React?

We can render a list using map() function.

function App() {
    const fruits = ['Apple', 'Mango', 'Grapes'];
    return (
        <ul>
        {fruits.map((fruit, index) => (
            <li key={index}>{fruit}</li>
        ))}
        </ul>
    )
}

What is a key in React?

Key is used as attribute in React to monitor the list changes. Keys help React identify each item in an array. If no key attribute is provided to list items, React throws warning message.

function App() {
    const languages = ['Javascript', 'Java', 'Python'];
    return (
        <ul>
        {languages.map((language, index) => (
            <li key={index}>{language}</li>
        ))}
        </ul>
    )
}

index as key is not recommended. Key should be unique.

What are hooks?

Hooks in React were introduced in v16.8. It is used to handle state and react features in functional component. Hooks are just functions that provides state and lifecycle features from functional component.

Following are few examples of built in hooks-

  1. useState - used to manage component state
  2. useEffect - used to manage side effects
  3. useMemo - used to manage complex computation and return cached result
  4. useCallback - used to prevent re creation of functions inside component

useState

const [id, setId] = useState();
// id - variable
// setId - function to update value of id

useEffect

useEffect(() => {
    // runs on every render
});

useEffect(() => {
    // runs on first render
}, []);

useEffect(() => {
    // runs when value of id changes
}, [id]);

useState(() => {
    return () => {
        // runs before component is unmounted
        // write clean tasks here
    }
});

useMemo

const cachedResult = useMemo(() => {
    // expensive calculations
    return result;
}, [dependencies]);

useCallback

const cachedFunction = useCallback(() => {
 // function logic
}, [dependencies]);

What are the rules for hooks

Following are the rules for hooks-

  1. hooks must be called at top level
  2. hooks should not be called inside loops, condition blocks
  3. hooks must only be called from functional components

Only hooks and components can call other hooks

How to create custom hooks?

Custom hooks provide a common functionality which can be used throughout the application. A custom hook might use built-in hooks to perform a common task.

You can create a custom hook as follows-

// custom hook
function useFetch(url) {
    const [result, setResult] = useState();
    useEffect(() => {
        fetch(url)
        .then(res=>res.json())
        .then(data=>setResult(data));
    }, []);

    return result;
}

// functional component
function App() {
    const result = useFetch('https://jsonplaceholder.typicode.com/todos');

    // component logic
}

API fetch logic is moved to a separate hook which can now be used by any other functional component or a hook

hook names must always start with use

What are refs?

Refs are javascript objects with a property 'current'. It is used to access DOM elements or store values inside React component.

createRef is used in class component and useRef is used in functional component.

Below is the example to focus on input box using ref-

Class component

import React, { Component } from 'react'; 

class App extends Component { 
    constructor(props) { 
    super(props); 
        this.inputRef = React.createRef(); 
    }

    focusInput = () => { 
        this.inputRef.current.focus(); 
    }

    render() { 
        return ( 
            <> 
                <input type="text" ref={this.inputRef} /> 
                <button onClick={this.focusInput}>Focus</button> 
            </> 
        ); 
    } 
} 
export default MyComponent; 

Functional component

import { useRef } from 'react';

export default function App() {
  const inputRef = useRef(null);

  function focusInput() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus</button>
    </>
  );
}

Updating ref value does not re-render the component

What are Higher Order Components?

Higher Order Components (HOCs) are React components that receives a component as input and returns a new enhanced component.

E.g.

// HOC
function withLayout(Component) {
    return function Layout(props) {
        return (
            <>
                <header>Header</header>
                <Component {...extraProps} {...props} />
                <footer>Footer</footer>
            </>
        )
    }
}

// Component
function App() {
    const Layout = withLayout(Dashboard);
    return <Layout prop={value} />
}

HOCs can be used to create common components, handle authentication, logging etc

What is Context API?

Context API is way to share data between components without passing props through components. It prevents prop drilling and make easier to manage data across application.

Context can be created using createContext() function and context data can be access using useContext hook.

E.g.

const defaultValue = {isLoggedIn: false};
const AuthContext = React.createContext(defaultValue);

// Provider component
const AuthProvider = ({ children }) => {
  // The context data
  const [authData, setAuthData] = useState(defaultValue);

  return (
    <AuthContext.Provider value={{authData, setAuthData}}>
      {children}
    </AuthContext.Provider>
  );
};

// Consumer component
const Dashboard = () => {
    const {authData} = useContext(AuthContext);
    return authData.isLoggedIn ? 'Authorized' : 'Unauthorized';
}

const App = () => {
  return (
    <AuthProvider>
        <Dashboard />
    </AuthProvider>
  )
};

Explain Redux

Redux is a tool for performing application state management. It is easily integrated with React and can be used with other UI libraries as well.

What are the characteristics of Redux?

Following are the characteristics of Redux-

  1. Single source of truth - Application will have a single store where global state is saved and which can be access across different component
  2. Read only - State is only updated by dispatching actions
  3. Pure functions - State is updated using pure functions (reducers)

What are the components of Redux?

Following are the components of Redux-

  1. Action - It is an event that is called with type and payload. Type tells reducer how to update the data and payload is the actual data
  2. Dispatch - It is a function that is used to dispatch any any action to reducer
  3. Reducer - It is a pure function that ultimately updates the store
  4. Store - It is an object which has global state which is only updated by actions.

E.g.

// Initial State
const initialState = {
  count: 0
}

// Function to update store based on action type
function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 }
    case 'DECREMENT':
      return { ...state, count: state.count - 1 }
    default:
      return state
  }
}

// Store object (as part of redux package)
const store = createStore(counterReducer)

// Dispatch action (as part of react-redux package)
const dispatch = useDispatch();
dispatch({type: 'INCREMENT'});
dispatch({type: 'DECREMENT'});

// Accessing state (as part of react-redux package)
const count = useSelector(state=>state.count);

Redux data flow Redux data flow

What is Redux thunk?

Redux thunk is used to handle asynchronous operations. With Redux thunk, dispatching of actions can be delayed. It is a middleware that can be used to write both synchronous and asynchronous logic.

E.g.

// thunk action creator
export function getUser() {
  // thunk function
  return async function getUserThunk(dispatch, getState) {
    const user = await fetch('/get/user');
    dispatch(setUser(user));
  }
}

What are controlled components?

In Controlled components, form elements are controlled by state values and is updated with user input.

function Form() {
    const [name, setName] = useState('');
    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(name);
    }
    return (
        <form onSubmit={handleSubmit}>
            <input type = "text" name = "name" value = {name} onChange = {(e) => setName(e.target.value)}>
            <input type="submit" value="Submit" />
        </form>
    )
}

What are uncontrolled components?

In Uncontrolled components, form elements are controlled by refs (DOM).

function Form() {
    const nameRef = useRef();
    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(nameRef.current.value);
    }
    return (
        <form onSubmit={handleSubmit}>
            <input type = "text" name = "name" ref={nameRef}>
            <input type="submit" value="Submit" />
        </form>
    )
}

What are fragment?

Fragment in React is used to group together and return multiple elements without adding extra nodes.

E.g.

function App() {
    return(
        <React.Fragment>
            <h1>Hello World</h1>
            <p>This is Home page</p>
        </React.Fragment>
    )
}

There is a shorter way to use Fragment

function App() {
    return(
        <>
            <h1>Hello World</h1>
            <p>This is Home page</p>
        </>
    )
}

What is React Router?

React Router is a library for handling page routes and overall application routing. React default does not manage routing.

react-router-dom package can be used to integrate routing functionality to React applications.

E.g.

import { BrowserRouter, Routes, Route } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} exact />
        <Route path="about" element={<About />} />
        <Route path="contact" element={<Contact />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

To navigate to different pages, Link tag can be used.

E.g.

import { Outlet, Link } from "react-router-dom";

function Navigation () {
  return (
    <>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/contact">Contact</Link>
          </li>
        </ul>
      </nav>
    </>
  )
}

How to achieve lazy loading in React?

Lazy loading is a design pattern. It reduces the initial loading time by loading components only when they are required.

To achieve lazy loading on React, we can use lazy() function which takes a callback to load a component.

E.g.

const Component1 = React.lazy(() => import("./Component1.js"));
const Component2 = React.lazy(() => import("./Component2.js"));

In above example, Both components will not load initially. Components will only load when it is required.

This is also known as Code-Splitting

We can use Suspense component from React to show some loading screen till component gets loaded.

E.g.

import { Suspense } from "react";
const Component1 = React.lazy(() => import("./Component1.js"));
const Component2 = React.lazy(() => import("./Component2.js"));

function App({isLoggedIn}) {
    {isLoggedIn
    ? <Suspense fallback={<div>Component1 loading...</div>}>
        <Component1 />
      </Suspense>
    : <Suspense fallback={<div>Component2 loading...</div>}>
        <Component2 />
      </Suspense>
    }
}

Explain Error Boundary

Error boundary is a concept introduced in React 16. Error boundary is a React component that catches error in any of its child component. Using Error boundary component, we can log the error and show a fallback screen with error details.

Error boundaries do not catch errors for:

  1. Event handlers
  2. Asynchronous code
  3. Server side rendering
  4. Errors thrown in the error boundary component (itself)

You can create Error Boundary as follows-

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // this updates the state
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // logic to create logs or any operation with error information goes here
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong</h1>;
    }

    return this.props.children; 
  }
}

Now, Error Boundary can be used inside any of the component

function App() {
    return (
        <ErrorBoundary>
            <Comp1 />
            <Comp2 />
            <Comp3 />
        </ErrorBoundary>
    )
}

Errors in any components which are children of <ErrorBoundary /> will be caught and handled as specified.

What is Server Side Rendering?

Server side rendering (SSR) is a technique where HTML is rendered on server and then sent to client to be displayed on webpage.

Advantages of SSR-

  1. Increased Performance - HTML is rendered on server which decreases the load on client
  2. Improved SEO - Search engines can easily index the web page contents (title, meta info, headings etc)
  3. Faster initial load - Due to SSR, client does not need to perform the rendering. Hence, page loads fast.

ReactDOMServer from 'react-dom/server' package is used to create static HTML string

ReactDOM.hydrateRoot is used to hydrate a container whose HTML was rendered by server

What are portals in React?

Portals are used to render a DOM node outside DOM hierarchy of the parent component.

You can create a React Portal as follows-

// it will render childNode inside containerNode
ReactDOM.createPortal(childNode, containerNode);

React Portal are often used to create modal boxes

How to style React components?

Following are few ways to style React component-

  1. Inline style
function App() {
    return(
        <div style={{width: '90%';height:' 80px';color: '#444';}}>
            Hello World
        </div>
    )
}
  1. Normal CSS import

App.css

.box {
    width: 90%;
    height: 80px;
    color: #444;
}

App.jsx

import './App.css';

function App() {
    return(
        <div className="box">
            Hello World
        </div>
    );
}

In React, className keyword is used instead of class

  1. styled-components
import styled from "styled-components";

const Div = styled.div`
    width: 90%;
    height: 80px;
    color: #444;
`;

function App() {
    return(
        // Div is a styled component
        <Div>Hello World</Div>
    );
};
  1. CSS modules

App.module.css

.box {
    width: 90%;
    height: 80px;
    color: #444;
}

App.jsx

import css from './App.module.css';

function App() {
    return(
        <div className={css.box}>
            Hello World
        </div>
    );
}

CSS modules are helpful in resolving CSS class names conflict. Here, CSS is scoped locally for the specific file.

What is memo in React?

React memo is a higher order component that prevents re-rendering of component when its props are unchanged. When wrapped around any component, it returns the memoized result which improves performance.

E.g.

function Dashboard({name}) {
    return <h1>Dashboard - {name}</h1>
}

export default React.memo(Dashboard);

Here, Dashboard will only re-render when name prop is changed. Dashboard would still re-render if any state, context change occurs inside component.

What are Synthetic Events in React?

React Synthetic Events are cross-browser wrappers around the browser's original event.

What is Webpack?

Webpack is a JavaScript build tool and module bundler that is used compile modules and manage dependencies. It take different files from application and outputs single bundle that can be loaded by the browser.

What is React Native?

React Native is an open source framework used to build cross platform mobile applications. Once the application is developed, it can be used in different platforms like Android and iOS. It uses native APIs to render components in different environments.