Recent

6/recent/ticker-posts

Top 100 ReactJS Interview Questions

1) What is react? 

  - open source javascript library 

  - used for building use interfaces 

  - simplifies creation of SPA using reusable component


2) What are the key feature of React ? 

  - virtual DOM 

  - component based architechture

  - reusability and composition 

  - JSX 

  - declarative syntax 

  - Community system 

  - react hooks 


3) What is DOM ? difference between HTML and DOM ?

  - DOM - document object model 

  - represent web page as tree like structure

  - allows js to dynamically access and manipulate content of web page 


  HTML - hyper text markup language 

  - it is just language

  - html will be represent as DOM tree in memory 


4) What is virtual DOM ? difference between dom and virtual dom ? (igeek)

  - Dom is real without it any web app can not interact or handle js 

  - virtual dom is only specific to react

  - in real dom when there is small change it will re render whole layout which is time consuming 

  - in react app, react library will make exact copy of real dom and show it - is virtual dom 

  - virtual dom only render the changes and whole page

  - in background react library keep comparing the changes in virtual and real dom and only the changes will be updated in real dom 

  - this update process is done by react library, is called reconcilation 


5) What are react components ? What are the main element of it?

  - building block of react app

  - reusable independed piece of UI which makes combined UI

  - class or function based 


6) What is single page application?

  - web app which has only single web page. 

  - content is dynamically updated without refreshing or loading new page   


7) What are the avantage of react?

  - we can built SPA 

  - open source (free to use)

  - lightweight and very fast (virtual dom)

  - supported by large Community 


8) Disadvantage of react ?  

  - for static web apps it is not choice


9) What is role of JSX in react?

  - javascript xml 

  - use to write HTML like code 

  - jsx is converted to javascript using tool like babel 

  - it is easy to write and read code  

  - use to write declarative syntax in react 


10) What is difference between declarative and imperative syntax?

  - declarative

    - focus on desired output without specifying step by step process 

    - jsx is used to write declarative syntax


    function App(){

      return <h1>Hello</h1>

    }


  - imperative 

    - involve step by step process for same output 

    - javascript has imperative syntax    


     function App(){

      const element =document.createElement("h1")

      element.textContent = "Hello"

      document.body.appendChild(element)

    }


11) What are the main file in react ?

  - index.html - single page for react app 

  - App.js - main container or root component 

  - index.js - entry point for js, render main react component(App) into root dom element


12) What is role of index.html ?

  - index.html is single page of react which render when any user request


13) How react provides reusability and composition ?

  - reusability - we can re-use component in app - header has one small component

  - composition - creating new component by combining small components - App.js has many component


14) What are state, stateless, stateful, and state management ?


15) What are props ?

  - way to pass data from parent to child component 


16) What is NPM ? What is role of node module ?

  - used to manage dependency of project

  - install, manage and share package of javascript


17) What is role of public folder ?

  - contain static asset that are served directly to user browser

  - image, font etc 


18) What are role of src folder?

  - src folder is use to store all the source code of app 



19) What is role of reactDom in react ?

  - react dom is javascript library that render component to DOM or browser

  - index.js is js file that replace root element of index.html with newly render component


20) What is function and return in App.js ?

  - it takes props as arg and returns jsx 

  - return is use to return element from function  


21) What is babel ?

  - used to transpile jsx to js 


22) What is fragment ?

  - group multiple element without adding additional Dom element


23) What is spread operator ?

  - used to spread an array or object     


24) difference between compiler and transpiler ?

  - Transpiler -Babel - tool to convert code from high level language(JSX) to another high level language(javascript)  

  - Compiler -high level language to low level language


25) What is  function and class component ?

  - functional component 

    - it is javascript function

    - stateless but with help of hooks we can manage state 

    - lifecycle methods  - no 

    - more readable 

    - this keyword - no 

    - render method -no 


  - clas component - defined using javascript classes 

    - stateful component using lifecycle methods

    - render method is responsible for returning jsx

    - lifecycle methods - yes 

    - less readable 

    - this keyword - yes 

    - render method - yes


26) What is prop drilling? 

  - process of passing props from high-level component to a deeply nested component through multiple layers of component 

  - solution of it is redux and context 


27) How to pass data between class component ?

  - this.props is used in child component to access data from parent component


28) What is role of this keyword?

  - refer to instance of class 


29) What is routing and router ?

  - routing - allows to create SPA with navigation without need of refresh 

  - react router - library for handling routing 

                 - way to define different routes and their corresponding component 

                 - enable navigation and rendering of different component based on URL 


30) What are hooks ? (igeek)

  - react hooks are react function provided by react 

  - allow function component to use state and lifecycle feature

  - way to provide stateful logic - managing component state, performing side effect, using life cycle methods 


31) What is useState() hook?

  - enable function component to mange state 

  - accept initial state as param and return array

  - the first ele is current state 

  - the second ele is function to update state 


32) What is useEffect() hook?

  - used to perform side effect in function component - data fetching, subscription or ops which need to be performd after initial render 

  - What is side effect - when page initialy render but data from api take time to render is call side effect 


33) What is useContext hook?

  - to access within components provied by context provider


34) What are controlled component ?

  - component whose form element can be controlled by state 


35) What are difference bet controlled and uncontrolled component? (igeek)

  - controlled

    - value are controlled by react state 

    - event handler update react state 

    - re-render on state change 

    - recommended and statndard practice of form handling 

  - uncontrolled 

    - value are not controlled by react state 

    - no state update 

    - useRef() used to change value 

    - less re-rendering 

    

36) What is code splitting?    

  - technique to split javascript bundle into smaller chunk which are loaded on demand 


37) how to implement code splitting in react ?

  - use react.lazy method to lazily import component - component is loaded only when needed

  - wrap component with suspense method to handle loading  

  - suspense component is use to display a fallback ui while lazily loaded component is being fetch


38) What is higher order component ?

  - component which takes another component as argument and adds extra feature to it  


39) What is importance of key in react?  

  - help react to identify which item have changed, added or deleted in list


40) What is react context?

  - way to share data between component without passing through every level of component

  - it creates context provider to provide data and consumer to consume data.


41) What is render()?

  - it returns JSX 

  - it is called whenever updates to state or props 


42) Use of setState()?

  - use to update state of component

  - when called react re-render component with updated state

  - any child component also re-render


43) What is useRef()? (igeek)

  - creates a ref object that can hold value across render


44) What is useMemo?

  - memoize value to prevent un-necessary re-computation

  - react will reuse the previous result untill a and b changes

  const result = useMemo(()=>{return a + b},[a, b])


45) What is useCallback()?

  - memoize function to prevent un-necessary re-creation

  - useful when passing callback as dependency to child component

  const handleClick = useCallback(()=>{},[])


46) What is difference between state and props ?

  - props are read-only (immutable)                 - State is mutable

  - props to pass data from one to other component  - state holds information within component

  - Props can be accessed by the child component    - State cannot be accessed by child component

  - Stateless component can have Props.             - Stateless components cannot have State  

  - Props are external and controlled by            - The State is internal and controlled by

    whatever renders the component.                   the React Component itself.

      

47) What is webpack ?

  - Webpack is module bundler for JavaScript. 

  - It takes various assets, such as JavaScript files, CSS stylesheets, and images, and bundles them together


48) What is in public folder ?

  - used to store static assets

  - %PUBLIC_URL% to access public asset


49) What is pws ?

  - a web server that individuals use for hosting their own websites or web applications

  - These servers allow individuals to have full control over their web hosting environment


50) What is robots.txt ?

  - Robots.txt is a text file placed on a website's server

  - It instruct web robots (typically search engine crawlers) on how to crawl and index pages on that site.

  - It tells web robots which pages or files the crawler can or cannot request from a website


51) What is node module ?

  - Node modules are encapsulated units of code that serve a specific purpose, such as handling file I/O, processing data, making HTTP requests, etc

  - These modules can be built-in Node.js modules part of the Node.js core

  - or they can be third-party modules distributed via the npm

  - Node modules promote code reuse, modularity, and maintainability in Node.js projects


52) If I have const obj = {name :"riya"} What will be obj if we assign => obj.name = "siya" ? 

  - console.log(obj) => {name :"siya"} (semicolon interview)


53) What is jslint and eslint ?

  - both popular linting tools for JavaScript, 

  - serve the purpose of analyzing JavaScript code for potential errors and enforcing coding standards

  JSLint:

    - JSLint has a very strict set of rules.

    - It doesn't offer much configurability, and it enforces its rules quite rigidly.

    - JSLint focuses on maintaining a consistent coding style and preventing common programming errors.

  ESLint:

    - It was developed to address some of the limitations of JSLint and to provide developers with more control over their linting rules.

    - ESLint is highly configurable, allowing developers to customize rules, define their own rules, and even share configurations with others.

    - It supports ECMAScript standards and has plugins for JSX, TypeScript, and more.


54) What are the testing framework use in js and nodejs ?

  - Mocha, Jest, Jasmine, Chai, Sinon


55) What is difference between map and filter ?

  - Map - Used when you want to transform each element in an array 

  - Filter - Used when you want to select only certain elements that meet a specific condition.


56) What is prototype and how it works ?

  - a prototype typically refers to a basic working model or mock-up of a website or web application

  - it is demonstration of the key features, functionalities, and layout of the final product before full-scale development begins. 


57) What is difference between call, apply and bind ?

  - methods to set the value of this explicitly when invoking a function, and also to pass arguments to the function


  - Use call when you know the number of arguments the function requires and want to invoke it immediately.


  Ex:-

    function greet() {

      return `Hello, ${this.name}!`;

    }


    const person = { name: 'John' };

    console.log(greet.call(person)); // Output: Hello, John!


  - Use apply when you have the arguments in an array and want to invoke the function immediately.


    Ex:

      function greet(greeting) {

        return `${greeting}, ${this.name}!`;

      }


      const person = { name: 'John' };

      console.log(greet.apply(person, ['Hi'])); // Output: Hi, John!


  - Use bind when you want to create a new function with a specified this value and optional 

  arguments, without immediately invoking it.


  Ex: 

    function greet(greeting) {

      return `${greeting}, ${this.name}!`;

    }


    const person = { name: 'John' };

    const greetPerson = greet.bind(person, 'Hi');

    console.log(greetPerson()); // Output: Hi, John!


58) What is difference between spread operator and rest operator ?

  - the spread operator is used for expanding elements

  - the rest operator is used for collecting elements into an array 


  Spread Operator:

    - It is used to expand an iterable (like an array, object, or string)

    - It is used to make copies of arrays or objects, concatenate arrays, pass arguments to functions, or create shallow copies of objects.


    const arr1 = [1, 2, 3];

    const arr2 = [...arr1, 4, 5]; // Copies arr1 and adds elements


    const obj1 = { foo: 'bar' };

    const obj2 = { ...obj1, baz: 'qux' }; // Copies obj1 and adds a new property


  Rest Operator:

    - The rest operator is used to represent an indefinite number of arguments as an array within a function parameter.

    

    function sum(...nums) {

      return nums.reduce((acc, curr) => acc + curr, 0);

    }


    console.log(sum(1, 2, 3, 4, 5)); // Output: 15


59) What is difference between element and component ? 

  - element" typically refers to a single HTML element that can be manipulated using JavaScript DOM

  - "component" is a reusable and modular piece of code that encapsulates a part of a UI 


60) What is pure component ? 

  - It is component for optimizing performance by shallow comparison of props and state.

  - It is to prevent unnecessary re-renders when the component's props and state haven't changed

  - By default, React re-renders a component whenever its parent re-renders, regardless of whether the component's props or state have changed

  - Pure components automatically perform a shallow comparison of the current props and state with the next props and state to determine whether the component should re-render.

  - If the props and state are the same, React skips the render process, resulting in better performance.


  const MyPureComponent = React.memo(function MyPureComponent(props) {

    // Your component logic here

  });


  - React.memo performs a shallow comparison of props by default. 

  - React.memo takes the functional component as an argument and returns a memoized component.

  - The memoized component will only re-render if the props passed to it have changed.



61) What is reduce function? 

  - The reduce function is used to iterate over an array and accumulate a value based on all the elements in the array.


  const numbers = [1, 2, 3, 4, 5];

  const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

// sum will be: 15


62) What is arrow function? 

  - concise way to write anonymous functions

  - Lexical this binding: Arrow functions don't have their own this context. 

  - This behavior can be advantageous when working with objects or callbacks, as it avoids issues related to this binding.

  - arrow functions do not have their own arguments object


63) What is difference between observables and promises?

64) Mention Higher order component's practical uses (igeek) 

  - They are functions that accept a component as an argument and return a new component with enhanced functionality


  1) Authentication and Authorization - to protect routes or components that require authentication or specific user roles

  2) Logging and Error Handling - to add logging or error handling logic to components.

  3) Error Handling - HOC could catch errors thrown by a component and display an error message or fallback UI

  4) Contextual Data: -withTheme HOC could provide a theme object to a wrapped component, allowing it to access theme-specific styles or configurations.

  5) Performance Optimization - withMemoization HOC could memoize the result of a computation and prevent unnecessary re-renders.

  6) Testing: HOCs can facilitate testing by providing mock implementations or injecting dependencies into components.

  7) Code Splitting: - withLazyLoading HOC could lazily load a component or module when it's needed, improving application performance and reducing initial bundle size.


// withAuth.js - Higher Order Component for authentication


  const withAuth = (WrappedComponent) => {

    return class extends Component {

      constructor(props) {

        super(props);

        this.state = {

          isAuthenticated: false,

        };

      }


      componentDidMount() {

        // Check if user is authenticated (e.g., by checking localStorage, session, etc.)

        const isAuthenticated = /* Your authentication logic */;

        this.setState({ isAuthenticated });

      }


      render() {

        const { isAuthenticated } = this.state;

        // If authenticated, render the wrapped component; otherwise, render null or a different component

        return isAuthenticated ? <WrappedComponent {...this.props} /> : <div>You must be logged in to view this content.</div>;

      }

    };

  };


  // ExampleComponent.js - Example component that requires authentication


  const ExampleComponent = (props) => {

    return (

      <div>

        <h1>Authenticated Component</h1>

        <p>This component requires authentication.</p>

      </div>

    );

  };


  export default withAuth(ExampleComponent);



65) What is difference in react and next routing? 

  React Routing:

  - React has routing library 

  - React Router primarily focuses on client-side routing

  - React Router supports code splitting out of the box, allowing you to lazy load routes and improve the performance of your application


  NextJS Routing:

  - Next.js has built-in routing. You don't need to install any additional libraries for routing  

  - Pages in Next.js are automatically mapped to routes based their file structure within the pages

  - Next.js supports both server-side rendering and static site generation

  - Next.js uses a file-based routing system, where each JavaScript file in the pages directory corresponds to a route in the application. 

  - Next.js automatically splits code at the page level, so each page only loads the JavaScript necessary for that specific page.


66) What is state management?

  - State management refers to the process of managing and controlling the data (state) within an application or system.

  - Storing Data, Updating Data, Sharing Data

  - Context API, Redux, MobX is use to manage state


67) What is ref in react? 

  - ref is reference to a DOM element or an instance of a component.

  - to access and modify DOM elements without using props, states


68) What is forwardref in react?

  - ForwardRef is a higher-order component provided by React that allows you to forward refs from a child component to a DOM element or another component.


  const FancyInput = forwardRef((props, ref) => (

    <input type="text" ref={ref} {...props} />

  ));


  // Usage example

  const MyComponent = () => {

    const inputRef = React.useRef();


    React.useEffect(() => {

      if (inputRef.current) {

        inputRef.current.focus();

      }

    }, []);


    return <FancyInput ref={inputRef} />;

  };


FancyInput is a functional component that forwards the ref to the underlying <input> element. 

Then, MyComponent utilizes FancyInput and forwards a ref to it. 

Finally, MyComponent utilizes that forwarded ref to manipulate the input field, focusing on it when the component mounts


69) What is interceptor?

  - an interceptor typically refers to a mechanism for intercepting and handling HTTP requests and responses.

  - Interceptors are commonly used to perform tasks such as adding authentication tokens, logging requests, handling errors globally, or transforming request/response data.


  Example:


    // Add a request interceptor

    axios.interceptors.request.use(function (config) {

        // Do something before request is sent

        console.log('Request Interceptor Triggered');

        return config;

    }, function (error) {

        // Do something with request error

        return Promise.reject(error);

    });


    // Add a response interceptor

    axios.interceptors.response.use(function (response) {

        // Do something with response data

        console.log('Response Interceptor Triggered');

        return response;

    }, function (error) {

        // Do something with response error

        return Promise.reject(error);

    });


70) What is react fiber?

  - React Fiber is to improve the performance and responsiveness of React applications.

  - The term "fiber" refers to the data structure used in this new implementation.

  - React Fiber allows rendering to be interrupted and resumed, This means React can pause rendering work to handle high-priority updates

  - By breaking down rendering work into smaller chunks, React can more effectively manage resources and respond to UI 

  - Fiber introduces the concept of priority levels for updates, allowing React to prioritize work based on its importance. 

  - With Fiber, React can handle errors more gracefully and recover from them without crashing the entire application.


71) What are react lifecycle methods? (igeek)

  - lifecycle methods are special methods that are automatically invoked at certain points in the lifecycle of a component

  - It allows developers to execute code at specific stages, such as when a component is first created, rendered, updated, or removed from the DOM


72) list all lifecycle methods and explain it? (igeek)

Mounting:

  - constructor(): This is called before a component is mounted. It is typically used for initializing state and binding event handlers.


  render(): This is the only required method in a React component. It returns the JSX that represents the UI of the component.


  componentDidMount(): This is invoked immediately after a component is mounted. It is often used to perform tasks such as fetching data from a server or interacting with the DOM.


Updating:


  shouldComponentUpdate(): This is called before rendering when new props or state are received. It allows you to control if the component should re-render or not.


  componentDidUpdate(): This is invoked immediately after updating occurs. It is useful for performing operations that require DOM updates or fetching data based on changes in props or state.


Unmounting:


  componentWillUnmount(): This is called immediately before a component is unmounted and destroyed. It is often used to perform cleanup tasks such as removing event listeners or cancelling network requests.


73) What is lazy loading? 

  - technique of delaying the loading of certain components or assets until they are actually needed

  - improve the initial loading time of a web application by loading only the essential resources required for the initial view

  - React.lazy() function allows to load a component lazily as a separate chunk when it's actually rendered


74) how can we achieve component unmounting functionality in functional component? (igeek)

  - using the useEffect hook with a cleanup function. 

  - The cleanup function runs when the component is unmounted.


  useEffect(() => {

        // Return a cleanup function

    return () => {

      // This function will be called when the component is unmounted

      console.log('Component is unmounted');

      // Perform any cleanup tasks here, such as unsubscribing from events, clearing timers, etc.

    };

  }, []); 


75) list all hooks (igeek)

  - useState: Allows functional components to have state.


  - useEffect: Enables performing side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.


  - useContext: Provides a way to pass data through the component tree without having to pass props down manually at every level


  - useReducer: An alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method (similar to Redux).


  - useCallback: Returns a memoized callback reference, useful for optimizing performance by preventing unnecessary re-renders in child components.


  - useMemo: Memoizes the result of a function, re-computing the value only when one of the dependencies has changed.


  - useRef: Returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). It's commonly used to access the DOM or to persist values across renders without causing re-renders.


76) What is difference between useEffect and useMemo? (igeek)

  - useEffect is used for handling side effects in functional components. Side effects may include data fetching, subscriptions, or manually changing the DOM.

  - useMemo is used for optimizing performance by memoizing the result of a function so that it is only recomputed when one of its dependencies changes.


77) What is protected route ? (igeek)

  -  protected route refers to a specific URL or endpoint within an application that requires authentication or authorization before granting access to its content or functionality. 


78) What is use of axios.create() ? (igeek)

  - The axios.create() method is used to create a new instance of Axios with custom configurations. 


79) In which scenario we can use useEffect? (igeek)

  - Fetching Data

  - Subscribing to External Events like scrolling, keyboard events, or WebSocket messages

  - Cleaning Up Resources like event listeners or timers

  - Updating Document Title based on state changes

  - to interact with Browser APIs like Geolocation API, localStorage, or sessionStorage.


80) What is recoilJS ? (igeek)

  - RecoilJS is a state management library for React applications


81) What is dynamic imports ? (igeek)

  - Dynamic imports can help optimize performance by loading modules only when they're needed, reducing initial load times and improving overall application responsiveness. 


82) What is benefit of using nextJS ? (igeek)

  - Server-Side Rendering (SSR) - improve initial load times and facilitate better (SEO)

  - Automatic Code Splitting - Next.js automatically splits code into smaller chunks, only sending the necessary JavaScript to the client

  - Built-in Routing - easily define routes for their application without needing to configure a separate routing library.

  - API Routes - we can build backend APIs without needing to set up a separate server.

  

83) can we use react hooks in server side component? (igeek)

  - No, React hooks cannot be used in server-side components

  - Hooks require the React runtime to manage state and lifecycle events, which is not available during server-side rendering.


84) how can we pass whole HTML from parent to child ? (igeek)

  - You can pass HTML content as a prop from the parent to the child component.


85) I have a API in my project which gives some static data and I don't want to recall that API, if page then also it should not be recall, don't use context and local storage

  - by storing the data in memory or using a caching library.


86) how can we pass props from child to parent ? (igeek)

  - by defining callback functions in the parent component and then passing those functions down to the child component as props. The child component can then invoke these callback functions with the necessary data as arguments.


87) What is destructuring ? (igeek)

  - It allows to extract values from arrays or properties from objects into distinct variables


88) What are use of yup? (igeek)

  - Form Validation - Yup can be used to validate user input in forms

  - API Payload Validation - used to validate incoming data payloads 

  - Error Handling - up provides error messages that can be helpful in informing users 

  - Data Transformation - converts strings to numbers or dates, before validating it against a schema.


89) What are methods in yup? (igeek)

  - string(): Specifies that the value being validated should be a string.

  - number(): Specifies that the value being validated should be a number.

  - boolean(): Specifies that the value being validated should be a boolean.

  - array(): Specifies that the value being validated should be an array.

  - object(): Specifies that the value being validated should be an object.

  - required(): Specifies that the field is required.

  - min(): Specifies the minimum value or length for the field.

  - max(): Specifies the maximum value or length for the field.

  - matches(): Specifies a regular expression pattern that the value must match.

  - email(): Specifies that the value must be a valid email address.

  - url(): Specifies that the value must be a valid URL.

  - nullable(): Allows the value to be null.

  - oneOf(): Specifies that the value must be one of a specified list of values.

  - notOneOf(): Specifies that the value must not be one of a specified list of values.

  - when(): Conditional validation based on other fields' values.


90) How to handle error in react ? (igeek)

  - Error Boundary Component:


91) What is difference between named and default exports? (igeek)

  - Named exports allow you to export multiple values from a single module.

  - Default export allows you to export only a single value from a module.

  - You can only have one default export per module.