Top 50 React Interview Questions and Answers for Freshers and Experienced for 2023

Posted in /  

Top 50 React Interview Questions and Answers for Freshers and Experienced for 2023

Paritosh Louhan
Last updated on October 19, 2022

    React , also known as ReactJS, is an open-source and free JavaScript library that helps developers around the world to create interactive user interfaces for web applications. The core feature of React is its reusable components that help in faster development. This is possible because you can easily use a React component several times within a single application.

    Lately, the demand for React developers has increased exponentially in the market. React has been considered the fastest-growing framework available. Many companies are opting for React to create their front-end applications. The developers around the world are working on getting the React certifications so that it can help in clearing the interview. Clearly, React is winning, and there is no end to its applicability.

    By keeping this in mind, we have created a list of top 50 React interview questions, along with answers, in this blog post. You can go through this list before appearing for an interview and ace it.

    So, let us begin with our list!

    Top 50 React Interview Questions and Answers for Freshers and Experienced [2022]

    The questions are categorized into three levels so that you can read according to your band level. Go through each question in order, and it will definitely help you to score better in your next React interview.

    React Interview Questions for Freshers

    1. What is React?

    React is a JavaScript library. The main highlight of React is its reusable components that allow faster development and JSX that allows us to write HTML-like-code in Javascript.

    2. What is a React Component?

    Components are the smallest logical unit in any React application. It is a set of reusable code and works the same way JS methods work.

    3.cHow many types of React components are there?

    There are four types of React components, as follows:

    • Functional Components
    • Class Components
    • Pure Components
    • Higher-Order Components

    4. What is a functional component?

    A basic JavaScript function takes props as input and returns JSX. This component is also known as “dumb” or “stateless” components. It is static and displays data as it is.

    Example

    import React from 'react';
    
    const FunctionalComponent = () => {
    return (
    <div>
    <p>Hello Functional Component</p>
    </div>
    )
    }
    export default FunctionalComponent;

    5. What is a class component?

    Class components are the React application classes extending React components and containing predefined methods. In the class component, we can do the following:

    • Declare states of objects.
    • Use props to pass values among components.
    • Change the state of objects in lifecycle methods.

    Example

    import React from "react";
    
    class ClassComponent extends React.Component {
    render() {
    return <span>Welcome to techGeekBuzz</span>;
    }
    }
    
    export default ClassComponent;

    6. What is a pure component?

    Pure Component is a fix for some problems which were existing in React. Every component re-renders itself whenever the object’s state changes. Sometimes, this creates multiple re-rendering, and websites slow to load. Here pure components come into the picture. Pure components do not re-render themselves when the value of state and props changes.

    7. What is a higher-order component?

    Higher-order components is a JavaScript function that takes one component and returns a new component based on the input provided. It releases us from copying the same logic in every component. It is very similar to higher-order functions in JS.

    8. What is JSX in React?

    JSX stands for Javascript extensible markup language ( XML ). It gives us the leverage to write HTML code in direct JS files. Writing JSX with React applications is unnecessary, but people find it useful, so they do it.

    Example

    const obj = <h1>Have a good day!</h1>;

    9. What are props in React?

    Props are short for properties in React. Props are passed as arguments to React components. They can also be passed through an HTML code as an attribute.

    Example

    const obj = <h1 greet="day">Have a good day!</h1>;

    10. What is a state in React?

    A state is an object and part of a component that holds some information related to the changes being done in the application. This information may change during the life cycle of components. In React, it is a good approach to keep the number of stateful components low.

    11. How can we write comments in React JSX?

    Comments can be a single line or double line. Below is the way to write comments.

    * Single line comment */
    
    
    /* Multi line
    Comment */

    12. How to use styling in React?

    All the styling properties get boxed inside a JS object, and we can assign that object to the style attribute. Following is an example.

    Example

    const styleObject = {
    color: '#ffffff'
    };
    
    function Greet() {
    return <div style={styleObject }>
    Hi!
    </div>
    }

    13. What are refs in React?

    Refs or references are used to store references of react components. They come in handy when we need DOM measurements or to add methods to the components.

    14. What is a React Router?

    React Router is a routing library that will enable you to create web pages with unique URLs incredibly quickly. All the pages/components of the application have a flow and all the information about that flow is stored in the Router.

    15. How is routing done in React?

    React Router is a library that handles all the routing in the application. It maintains a unique structure and behavior for developing single-page web applications .

    16. What are the Router components of React Router v4?

    React Router v4 provides the following 3 components:

    • BroswerRouter - It is used to create browser instances.
    • HashRouter - It is used to create hash instances.
    • MemoryRouter - It is used to create memory instances.

    17. What is Redux?

    Redux is a container where the state of the application is stored. It is an open-source JS library . It is used with React, but people have used it with Angular for creating user interfaces.

    18. What are the components of Redux in React?

    Redux consists of three components, as follows:

    • Store - A store is an object that holds the application state. Redux can have only a single store in the application.
    • Action - Actions are the single truth of information for the store. Actions are like requests and have a payload. This payload is being carried from application to store.
    • Reducers - If any operation is being carried out and the state of the variable is changed then reducers are used. Reducer is a pure function that will accept the previous state of the application, calculate the next state and return the new object.

    19. How can we render components conditionally?

    We can render components conditionally by using if-else or by using ternary operators. Look out for the example below.

    const component = (name, salary) => (
    <div>
    <span>{name}</span>
    {salary
    ? <p>{salary}</p>
    : <p>{'salary is not available'}</p>
    }
    </div>
    )

    20. What is Virtual DOM?

    Virtual DOM is an in-memory illustration of real DOM. Whenever React renders any application, an in-memory tree-like structure gets created of the real DOM. Whenever any data changes, the real DOM gets compared with virtual DOM, and only those nodes are re-rendered, which are changed. So in a way, only some data is changed while the rest of the data remains as is.

    21. What is the use of keys in React?

    We can identify unique virtual DOM elements with the help of keys. React would re-order the DOM elements instead of re-rendering many nested DOM changes with the help of keys. This phenomenon can serve as a huge performance enhancement.

    22. Is it mandatory for each component to have a render function?

    Yes, it is mandatory for each component to have a render function.

    23. How can react component life-cycles be divided?

    React component life cycles have four phases, as depicted in the following table.

    Initial Phase

    Mounting Phase

    Updating Phase

    Unmounting Phase

    getDefaultProps()

    getInitialState()

    componentWillMount()

    componentWillRecieveProps()

    componentWillUnmount()

    componentDidMount()

    shouldComponentUpdate()

    render()

    componentWillUpdate()

    render()

    componentDidUpdate()

    24. What is Flux?

    Flux is the design architecture used by Meta to build applications, which is neither a library nor a framework. It handles complex data inside client-side applications and manages the data flow. It can have multiple stores and uses a dispatcher.

    25. What is prop drilling?

    When you have to pass data from parent to child but the parent component is way up in hierarchy then at that moment, we use prop drilling. It is a process of passing the data from parent to child and further to its subsequent child till it reaches the destination.

    React Interview Questions for Intermediate

    26. Can you update the state directly?

    We can update the state object directly by assigning values to them, but it's a bad practice. Updating the state doesn’t re-render the component. Instead, we use the setState() method. When we update the state through the setState() method, it changes the state, and post that, the component gets re-render so that new values are visible on the UI.

    Example

    this.setState({value: 'something'});

    27. Explain the difference between props and State.

    The following table highlights the key differences between props and State in React:

    Props

    State

    Props can be passed from one component to another.

    The state can be passed as props from one component if one component is the prop for its child component.

    Props cannot be changed over time.

    The state is mutable.

    They are used to pass data.

    They are used to store data.

    They are used to enhance performance.

    They are preferred less.

    28. What is the strict mode in React applications?

    A strict mode is a tool added in React version 16.3 and further to detect problems that can result in exceptions in the application. It provides warnings and can identify components with unsafe lifecycle methods. To enable strict mode, <React.StrictMode> tag is needed to be added to the application.

    Example

    import React from "react";
    import ReactDOM from "react-dom";
    import FunctionalComponent from "./FunctionalComponent";
    const root = document.getElementById("root");
    ReactDOM.render(
    <React.StrictMode>
    <FunctionalComponent />
    </React.StrictMode>,
    root
    );

    29. How to pass data between React components?

    There are two ways to pass the data between components as given below:

    • If data is passed from parent to child components, we can use props.
    • If data is passed from child to parent components, we can use events.

    30. What is the purpose of push() and replace() methods of history?

    push(): This method adds a new location to the array of visited locations.

    replace(): This method will replace the current location in the array with the new location.

    31. What are render props in React?

    Render props are the prop whose value is a function. It is used to pass data from one component to another. The below component uses render prop, which returns a React element.

    <DataProvider render={user => (
    <span>{`Welcome to techgeekbuzz ${user.name}`}</span>
    )}/>

    32. How to avoid using relative path imports in create-react-app?

    This can be achieved by adding the below tags in the .env file. Restart the development server, and now you can import anything without providing the relative path.

    ??NODE_PATH=src/app

    33. What is the difference between setState() and replaceState() methods?

    The following table shows how setState() and replaceState() methods differ from each other:

    setState()

    replaceState()

    Used to merge the current and previous states.

    It removes the current state and replaces it with the provided state.

    You can also set state to false/null in setState().

    No such provision available in replaceState().

    34. How to loop inside JSX?

    You can use Array.prototype.map with an arrow function to loop inside JSX. An example of the same is provided below.

    <tbody>
    {obj.map(element => <HomeComponent key={element.id} owner={element.user} />)}
    </tbody>

    35. What’s the difference between an Element and a Component in React?

    React Component is the smallest logical unit and core building block in a React application. In common language, React component is a JavaScript function or class that accepts input and returns a section of UI.

    Example

    function SpaceMission() {
    return <span>Hi, I am a spacex mission!</span>;
    }
    export default SpaceMission;

    An element, on the other hand, is the smallest DOM element that we see on screen.

    Example

    const element = <h1>Welcome to TechGeekBuzz</h1>;

    36. How to access the Redux store outside a component?

    Export the store from the module where it was created with createStore(). It will not pollute the global window object.

    Example

    store = createStore(myReducer)
    
    export default store

    37. Provide an example of a Jest test case.

    Consider you have a function titled multiply in the multiply.js file.

    const multiply = (a, b) => a * b
    
    export default multiply

    Create a file named multiply.test.js which contains actual test:

    import multiply from './multiply
    
    test('multiplies 5 and 2 to equal 10', () => {
    expect(multiply(5, 2)).toBe(10)
    })

    React Interview Questions for Experienced

    38. Can we use setState() in the constructor?

    setState() re-renders the components and their children. We might not need to use setState() in the constructor as the view is not rendered yet.

    39. Can we use setState() in componentWillMount()?

    Yes, we can.

    40. Can web browsers read JSX directly?

    Web browsers can never read JSX directly. They are built to read JS only. We can use Babel to convert JSX into JS to make browsers read that.

    41. Is there any difference between constructor and getInitialState()?

    getInitialState() is used to initialise state when we have created a component through React.createClass(). On the other hand, we can use a constructor for initializing things.

    42. Can a child component send back props to parents?

    No, a child component cannot send props back to parents. This factor greatly increases rendering efficiency when dynamic data is considered.

    43. Does React Hook work with static typing?

    Static typing is the phenomenon that occurs during the time of compilation to ensure all variables are statically typed. React Hooks, on the other hand, are functions that make sure all the attributes must be statically typed. We can make use of React APIs with custom hooks for enforcing stricter static typing within the code.

    44. How are hooks different from classes?

    React hooks are used to manipulate the state in functional components, whereas classes are used in class components. There is no need to add any constructor in hooks, whereas constructors are required in class-based components.

    45. Explain the working of the useRef() hook in React?

    The useRef() hook stores a mutable object that doesn’t render with the application when changes are made. It returns a ref object, and that object contains a .current property which contains the previous value.

    Example

    import React, {useState, useEffect, useRef} from 'react';
    
    function HooksDemoComponent() {
    
    const [count, counter] = useState(0);
    const counterHook = useRef(0);
    
    //increasing the value of counter on key press
    useEffect(() => {
    counterHook.current = counterHook.current + 5;
    });
    
    return (
    <div>
    <input onKeyDown={() => counter(count + 5)}>
    </input>
    <h1>The actual Count: {counterHook.current}</h1>
    </div>
    );
    }
    
    
    export default HooksDemoComponent;

    46. How to get query parameters in React Router v4?

    The feature of passing query strings was taken out from React Router v4. Currently, users can use a third party-library known as a query strings library. An example of the same is given below.

    Example

    const queryString = require('query-string');
    const parsed = queryString.parse(props.location.search);

    47. How to implement a default or NotFound page in React?

    To create a NotFound page, the user has to drop the path attribute.

    An example is provided below.

    <Switch>
    <Route exact path="/" component={Dashboard}/>
    <Route component={NotFound} />
    </Switch>

    48. How to perform automatic redirection after login?

    The react-router package provides a <Redirect> component. After rendering the <Redirect> component, it will navigate to a newer location. The current location will be overridden by this new location in the history stack.

    render() {
    if (this.state.isUserLoggedIn) {
    return <Redirect to="/redirect-page" />
    } else {
    return <div>{'Please login to continue.'}</div>
    }
    }

    49. What are the different ways to write mapDispatchToProps()?

    Below are the ways we can write mapDispatchToProps.

    Type 1

    const mapDispatchToProps = (dispatch) => ({
    action: () => dispatch(action())
    })

    Type 2

    const mapDispatchToProps = (dispatch) => ({
    action: bindActionCreators(action, dispatch)
    })

    Type 3

    const mapDispatchToProps = { action }

    50. How to add multiple middlewares to Redux?

    To add multiple middlewares to Redux, we can use applyMiddleware().

    import { createStore, applyMiddleware } from 'redux'
    const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore)

    Conclusion

    If you have read all the questions above and reached this point, you probably have gotten the basics of React fundamentals extremely clear. Start building an application to enhance your knowledge of each concept. If you find anything interesting or intriguing, comment below and let us know. We will be happy to help.

    Happy coding.

    People are also reading:

    FAQs


    As a React developer, you should be proficient in HTML, CSS, and JavaScript, have mastery in JSX, an in-depth understanding of node package manager (NPM) and Redux, familiarity with the React library, and basic knowledge of version control systems, like Git, DOM, and event handling.

    A React developer is basically a web developer who designs user interfaces for web applications using the React library. Also, they are in charge of creating new React components.

    Many developers begin their careers with a bachelor’s degree in computer science or any related field. Also, many organizations today are looking for candidates with bachelor’s degrees. So, it is better to earn a bachelor’s degree in CS.

    Firstly, gain mastery of HTML, CSS, and JavaScript. Make yourself familiar with the React library and its different aspects. Learn about React developer tools. Start creating small projects. In between, you can opt for earning certification to validate your skills. Create a portfolio of your work and enhance your resume. Finally, you can apply for a job.

    After you apply for jobs, meanwhile, you can keep practicing your skills so that your knowledge does not rust. You can even go through this article to get familiar with some top React interview questions that help you recollect concepts and prepare for your upcoming React interview.

    Leave a Comment on this Post

    0 Comments