hello and welcome to this session on the top react interview questions and answers by intellipad react a powerful JavaScript library developed by Jordan w a software engineer at meta however since its invention back in the 2013 programmers always had a mi reaction to it yet react was elected as the second most used web framework globally for 2024 with over 39% of developers using it another article by nascom highlights various reasons why you should pursue reactjs truth be told react may have its quirky aspects but with powerful features like the virtual dor hooks the condex API and a whole ecosystem of features it is a force to be reckoned with moreover the 8,000 plus job opportunities and an average annual salary of 4 lakhs further proves its demand and importance within the tech industry if you're still with me then let's get started with this video as mentioned earlier we're going to discuss 20 questions in this particular video which have been put together by our top 1% industry experts who have over 7 years of experience in the web development field before we begin if you want more such content then make sure to subscribe to our YouTube channel and hit the Bell icon to never miss out on an update from us so without wasting any more time let's Jump Right In with our first question on my list what is react and why is it popular react is a popular JavaScript library used for building powerful user interfaces its key strength lies in its ability to create component based architecture which allows developers to create reusable UI components additionally react's virtual Dom is able to create a copy of the real Dom that minimizes direct Dom manipulations which significantly boosts performance we'll discuss more about the virtual Dom in the upcoming slides so make sure to stick till the end moving on to our next question what is a single page application or Spa a single page application is a type of web application that loads a single HTML page and then instead of reloading the whole page only updates the affected parts of the page according to the users's actions like only rendering the color change here from light blue to Pink this means it only contacts the server for the components in which you have added new features or have made certain changes now this process results in Faster load times better responsiveness and smoother user interactions however using Spas can become a challenge when it comes to search engine optimization because the application uses a single URL so it becomes harder for the search engines to crawl and index content effectively moving on to our next question what is jsx and how does it differ from HTML jsx or JavaScript XML is a syntax extension for JavaScript that allows developers to write HTML like code directly into JavaScript files as you can see in this example a jsx file allows JavaScript code to be directly embedded within the HTML content unlike HTML applications another key difference between the two Li and jsx is compulsion to properly close all self-closing tags like the image tag The Brak tag which is also requirement in X HTML but not in your regular HTML now let's increase the difficulty a little bit by moving on to our next question explain the difference between functional and class components in a very straightforward way class components were used before hooks you can think of them as traditional large and complicated machines on the other side functional components came into use majorly after making them the modern easier to use choice in react the class components were extended from the react dot components and included the render method which returned jsx State changes inside the components are managed using this do state and updated with this do sect State functional components being used more frequently after the introduction of react hooks use hooks like use State and use effect to handle State and life cycle limits another difference between the two is that functional components used to be stat less but after the introduction of hooks they were able to manage States if you bring this point up the interviewer is very likely to bring up this next question what is the difference between a stateless and a stateful component in react stateless components do not manage or store their data they simply receive data via prompts and display it they are best used when you don't need to handle any logic and just want your content to be displayed on the user interface stateful components on the other hand can manage their own State and can update their existing state based on user interaction or other events this implies that they can handle complicated Logics and produce a required output as well with the introduction of react hooks you can choose to keep functional components to be either stateful or stateless we talked about prompts in this question so let's look into that further with our next question what are props in react and how are they used props or properties are a way to pass data from a parent component to a child component in react the child components cannot modify these values because they are read only so instead these values are used to trigger certain actions in the child components you must have understood at this point that both props and state are used to control and manipulate how components behave and render so it becomes crucial to understand the differences between them which brings us to our next question what is the difference between State and props interact state is a mutable object that stores Dynamic data meaning it stores data that changes over time due to other factors such as user interaction Network requests or other events such as the count variable here which increments or decrements its value based on user interaction props as mentioned earlier is an immutable object meaning the data cannot be modified another notable difference is that state is private and is fully controlled by the component it belongs to props on the other hand is controlled only by the parent component and cannot be changed by the children moving on to our next question what are control and uncontrolled components control components are used when you require control over the data being entered into a form such as in the case of form validation where you need to fetch the username and password to validate their authenticity uncontrolled components on the other hand are used when you do not need to dynamically inspect the user inputs such as a user subscribing to your newsletter or a user uploading a file in these cases react does not need to directly react to the inputs because the data is being sent to the for evaluation another important difference is that controlled components are accessed through the state attributes which makes it easier to change however since uncontrolled components are managed through a ref it becomes harder to access the values that's all you need to know about controlled and uncontrolled components now let's move on to our next question what is the purpose of the key attribute in react lists say if in this list containing apples bananas and orange I were to update only one of the fruit names say orange should the whole list be rendered no because it will be a waste of time since the other two elements never changed in our case react understood which element to rerender based on the key associated with that element key attributes as a name suggests is primarily used to identify each item uniquely when the list rerenders enabling react to track and update individual items in the list without having to reender the entire list moving on to our last question of this module what are fragments in react and why are they used fragments and react are a way to group together multiple elements without adding an extra node to the Dom like this H1 and P tags that are group together with react fragments without adding an extra containers around them in short fragments are used when you want to avoid unnecessary wrapper elements like this div tag and with that we reach the end of this module now let's start with our Advanced module with the first question we have or the 11th question that we have which is what is the virtual dorm and how does react use it to improve performance now what exactly is a virtual dor a virtual dor is a lightweight copy or a lightweight inmemory representation of the actual dor meaning when you are running a react component there are two Doms one is the original dor and one is the virtual dor but why would we need a virtual dor let me show you why look at this web page here we have a simple clickme button if you upon clicking on the clickme button your this pan element which encloses this particular number will change that is the number of times you click it will keep on increasing 1 2 3 4 and it will keep on going but just tell me about one thing if you look at both of these web pages there's only one single thing that is changing and that is this particular element or this particular number which is inside the span element so do we need to render every single component all over again do we need to really render this button then this paragraph and then this whole web page when only one particular span element is getting changed no because it'll waste a lot of time now although this web page is very small it's quite a small web page so you might not need to do a lot of work a lot of heavy lifting here but if this web page was a gigantic like I had a lot of elements a lot of styling and everything and then only one single span element is changing if react has to render the whole web page all all over again it will waste a significant amount of my time you don't need to do all of that and this is where virtual Dom comes to your rescue what virtual Dom does is whatever code you're writing it checks through or it Scrolls through your whole code to see what has changed so this is your Dom hierarchy and if you see consider this is your H1 element paragraph and these are the list elements so if you see in both of these codes let's say we only changeed the paragraph element so we don't need to render reender the H1 and the list elements because we didn't touch them we only changed a little bit of code in the paragraph element so only this particular change needs to be reflected in the actual Dom and that is what virtual Dom does only the changes that are made in the code are made to reflect in the original Dom and the rest of the components like our H1 and the list elements they're not made to render all over again moving on to our next question what are react life cycle methods and when are they used let's look at the technical definition first react life cycle methods are special functions that provide granular level control to developers to hook into specific points in a component's life cycle the reason why we need life cycle method methods is so that you can attach certain events to a component's life cycle that is when the component is first initialized it needs to do this and when it is like in um when it is about to end you need to do this wrap up all of this close these timers and do this and do that when the component is about to be closed off so to attach certain events to a component's life cycle is why you need the life cycle methods now there are three main phases in the life cycle methods that's the mounting phase the updating phase and the unmounting phase now these further have a lot of points under them and while we look into them one by one like this Constructor get derived straight from proms render and component did Mount but when we're looking into these I'll try to take an example a hypothetical example or maybe a real life example so that you have a better understanding of what what I'm trying to say so Constructor initializes the state and it binds methods say um let's take an example of a say a video game so when you're starting to play that game the initial State and everything is set yeah like the player score is set the player ID and everything is set to it's initialized right if you're a new player every single thing starts from zero so that is the construct the initial state next you have get derived state from prompts now what if you are an existing uh player you used to play before as well you just logged out from your computer yesterday now you you woken up you started your computer and you're ready to play so the stats must be fetched from somewhere and that is this get derived state from prompts when you have to fch fetch the data some pre-existing data and load this pre-existing data to the current value that is update State based on prompts before entering next you have render whatever changes happened the uh your database will try to fetch or the game will try to fetch the data from the database so if there is any data then that is rendered and shown on the dashboard of the game but if there is no data the user is completely new and the there is no database existing for the user already then there's no need to fetch the data so the origin dashboard only you can show to the user next component did Mount this is just making sure that everything is working perfectly and the game did was able to fetch everything and was able to display everything perform side effects such as API calls next you have the updating phase now there are a lot of functions in updating phase such as your get Drve state from prompts shoot component update render get snapshot before update and component did update again get derived state from prompts your player is playing the game ly right so at some point the player is able to gain some points or they or they lost some points So based on that you're collecting these points much like your virtual dorm you're collecting these points that the players the score right now is 10 now it it became 20 so the new update is there it's existing in the virtual do next shoot component update now we decide the second score that we have that is 20 10 is not equals to 20 right so the next score that we have is different from the original score which means it needs to be updated so in the shoot component update State react checks whether they need to compare whether they need to update the already pre-existing score or not render is after updating it renders the whole screen and shows the next updated uh value on the screen get snapshot before update is before updating the screen with the dashboard with the original values they need to make sure that the previous value is saved right the previous value say I had a score of 10 so that 10 that score with 10 should be saved somewhere and that is getting a snapshot before the update happens and before my score becomes 20 getting a snapshot of that then component update is again making sure that everything was set and all right lastly we have the unmounting state which consists of only one function that is component will unmount so when the component is unmounting there are certain things you need to make sure of clean up the resources and even listeners on subscription so whatever the player the players is session that was happening right now every single thing the connection to the database must be cut off and the score should be kept to zero back again because the game is shutting down anyways so all of these things comes under component will unmount and now moving on to our next question explain the use State and use effect hooks with examples now use state is basically used to store the fesh data and their loading States use State you can think of use State as a container um in which you store a particular value so say if you have a count variable so every single time I'm increasing the value of count it's stored inside this U State variable and every single time I'm increasing it the value the previous value is fetched from this U States's container use effect on the other hand is used to perform side effects uh like when you're making an API call so what happens in the background that is all controlled by use effects it is used to fet the data when the component mounts so such a if you are uh if you're setting up a clock or maybe there's a popup which is supposed to happen after a certain period of time all of these actions are important like a timer going on in the background um maybe a clock that is going on on your web page in the corner it is important but it should not mess around with the main part of your web page some function needs to make sure that this clock is continuously ticking in the background and at the same time the important parts of the web page are also loading that is where use effect comes in let me Show an example so you that you have a better understanding I'll just create a file called as components okay so inside this for use State let's just create a counter and we need use state as well here const count and set count we're going to initialize with them with the value zero we don't need this we need two functions here which will be increment which will in increase the value of count + one and we'll have a function called as decrement which will reduce the value of count as one now let's have a paragraph tag here which will display the current count which will show the count variable next we need two buttons this should increment the value on click going to call increment similarly we need one for decrement as well so I believe our counter function is set let us call it here in the app function mind okay counter now let's start our application npm start all right I haven't add added the styling that's why it looks a bit like this so don't mind that now if we click on the increment function you can see how the value is getting incremented if we click on decrement and we haven't set any limits so it might it will keep on going as much as I wanted to and that is how UST State UST State works now let me just quickly show you how use effect works as well so for use effect in the components let's just create a timer application oh okay we need use State anyways for use effect you need use State as well well so use effect and use State we don't need this and we need some we need seconds and set seconds you will have the UST State value of zero now this is the timer it will be it will just keep on happening in the background we need to call use effect here here use effect we're calling and it will keep on incrementing this counter on its own we need a set let's put it inside a variable uh I'll call it interval set interval and now I'm going to change the value of set seconds whatever the previous value will be your seconds it will be incremented by one and this will keep on happening every 1 second okay and then we're going to we need to clear it out as well clear the interval and okay so inside of this let's just add an H3 which will dis play the timer seconds all right now let's try importing the timer here as well all right let's look how our code looks all right the timer is already keep on happening in the background so that is use effect so I can keep on interacting with my main application here and this timer will also keep on happening in the background that's how use effect is working let me just stop this else my uh I'll just remove them from here okay else the timer will just keep on going on forever so let's move on to our next question which is our 14th question another interesting Concept in react what do you understand by props drilling props drilling it's like if you have multiple children in the same parent there's a parent there's a child there's a grandchild there's a grand grandchild now there's a possibility that one of the props that you're getting in the parent element now although the child element and the grandchild element do not want to use it but the grand grand or the great grandchild wants to use that particular prop so it needs to pass through all of these components as well it needs to pass through the parent it needs to pass through the child grandchild and then it will reach the great grandchild so even though the child and the grandchild really don't need to use a component they will still need to pass it through them so that the great grandchild gets it and that's where that's that becomes a problem if there are like too many nested elements what if it had even like a great great grandchild and just keep on going and then that would just become hectic at one point and you just lose track of where the prompt was actually supposed to go and where it actually went or in technical terms props drilling is when data has to be passed through many layers of components let me just show you an example because that's the easiest way to understand um so we need multiple components now we need a parent we need a child we also need a grandchild all right we'll start with the parent which is in here parent is the only component which is present in the app. js now consider this situation where parent is the only component that is present in app. js so whatever prompt we're getting from here from the parent component must be passed down so the grandchild component say in the app I'm going to import US state and in here I am setting the user oh I don't need to set the user I just create the user name uh what do you call him John age John is 30 years old okay so I'm passing this particular users's data to the parent component here I'll give it as a prop user now keep in mind that right now from parent child and grandchild only parent has the access to user now grandchild wants access to user as well but grandchild can only be accessed through the child element so in the parent element what I'm going to do I'm going to call the child and the user I am getting from here I'll have to pass it through here okay now this child component really doesn't need to use the user but still because grandchild is to the child element it will need to pass the user prompt through the child element so here I'm going to call grandchild and pass the value of user through child element and finally it will reach the grandchild element where it will uh show the the name of user or maybe just say hello name it was name yeah let me just remove these two I believe I'm not showing the grandchild component maybe I can just okay now you can see that how even though the parent and child components none of them used this user data still it was getting pass through the parent and the child and then the grandchild and only then the grandchild could use it now imagine if there were like maybe four or five even more components so it'll be like a b c d e f g and then G will get the component are you looking at how deeper the nesting just keeps on going and how hectic it can get so that is why props drilling is one of the cons of react and there is a wonderful way you can solve it let me show you what that wonderful way is that will bring us to our next question what is the context API and how is it used for State Management now context API is a way to solve the problem of this props drilling how what context API does is instead of the props having to go through all of these intermediary components context API can create a global variable or it can provide a global space where these variables will automatically get stored in so that whenever other variables or any other CH any other child components wants to get this variable they don't have to go and ask their parent where is the variable and then the parent ask their parent it doesn't have to be that way it can just directly go to This Global space and retrieve the component or retrieve the variable whatever it is looking for or in technical terms the context API and react is a feature that allows you to manage and share state or data globally across a component tree without needing to pass prompts manually at every single level let me show you the code for this um so for creating a context API you need to create a user context folder inside of which we're going to store the user context file okay I'm just going to call this as [Music] context because inside of this I'm going to create user context Js all right same here as well the difference is I'm going to call create context and I also need a use state to store the state of the variables so let me just export it here itself user context is create context I don't need this line all right here I'm going to call this user provider and this will have children just bear with me you'll understand what I'm trying to do when we reach the end of this but in the middle it might look a bit hectic and stressful but just be with me um now this is the function that we're going to export inside of this let's create user and set user we need the same thing right when we are returning it will not be a div it will be a user context.
provider the value will be user and inside of this we'll let the children and I believe that is everything we need all right so now if my grandchild component which was accessing the particular this hello. name um let me just remove everything from here for the parent as well we don't need to do any of this or this okay so now in the grandchild component in the app. js or maybe let's just have the child component I can show you how they're like still calling onto the function but they're not passing the values and still it's getting displayed okay so in the grandchild component um instead of this I can just import user context from this and alongside of this I'll need to call use context keep in mind this is use context and uh all right so now I can create a user here I can retrieve the value of user from here which is use context user context and I can just have hello user.
name okay let me just remove this all right let's see how that turned out to be all right we've done something wrong child is calling grandchild parent is calling Child app is calling let me just remove that all right so we need to wrap this up in user provider uh let's just wrap the p class in the user provider all right now let's look at the code so yeah it is showing the data over here uh and now we're able to directly access all right let me this welcome okay so now we're able to directly access the value of John which was only accessible to the parent component we're able to access that component uh in the CH grandchild component and as well and that is how kex API works so moving on to our next question what are higher order components Give an example in technical terms a higher order component is a function that takes a component as an input and returns a new component with additional functionality or modified Behavior this we even have higher order functions in other programming languages I believe we have it in Java as well where you take another function as an input and then you can return the function as an input as well so that's called as a high order function similarly here also say if you are having a web website in which in every some of the pages are only accessible to like say premium users so how do you make sure that every single web page which is accessible to premium user is authenticated to authenticate the premium users itself you need another function right or you need another component which is dedicated to authenticate the users now how do you apply it in every single page you cannot just go to every single page and manually type in the code that will be like a lot of work that is where higher order components come in because you can have one single higher order component which takes another component as an input you can keep it separately and in every single web page you can just integrate it with the other web pages which can reduce your time significantly so let me show you how this is going to work I'll guide you through every single step so just bear with me because this is also going to be a little bit hard so what we're going to do so we're going to create a hello world component and we're going to create another function a higher order function which is we're going to call it as a higher order function and this higher order function will take this hello world as the input the hello world will be coming from the hello world component it will be a whole file like this parent. JS hello world will be a hello world. JS file from that we'll take the hello world and this enhanced component will take hello world as its input and we'll just add maybe what like high hello world or some other prompt to this particular hello world and will return this will enhance it or will we just modify it let me show you what I'm trying to say so first we're going to create NH higher order component JS all right now we have to create a wrapped content wrapped component now this is the input the whatever input we're taking that will be inside this wrapped component um okay so we don't need multiple lines we're just going to return one function which will be in which will be enhancing or modifying the component I'm just going to go with enhanced component going to take the props and uh we're going to log into the console whatever the new modification is happening btic rendering app component dot name whatever name it is with props or just simplify it modifying with new props okay and we're just going to return this wrapped component plus oh whatever prompts that we made all right and we're just going to export that now we're going to create a hello world function or a hello world component and inside of this say we're taking a prompt say a name and we're just going to return hello not World whatever name is coming here we're going to return it right here let me an exclamation mark now what we're going to do inside the same function is I'm going to add that component I'm going to add the H component inside of this component so let me do that I'm just going to call it enhanced hello world I'm not typing it out now I'm going to call H and I'm going to pass hello world as the prompt inside of H let me close that you did not import I'll have to import H all right and instead of returning hello world I'm going to return enhanced hello world so all right so now let's just create our H component so what we're going to do is that we're going to create an H component we're just going to create it and then we're just going to keep it aside and in the meantime we'll create our another component say we we're going to call it say greed component and in that greed component we'll pass in the prompts and we're going to pass this greet component or this greet function into the HSC component let me show you how that is done so initially we need our H component and this is going to return wrapped component this will be the higher order function that will be this will be the other component that we'll be taking uh we're going to need a function enhanced component which will take props and it's going to log modified rra component with new props all right uh that's good to go and we have to return wrapped component plus props when we are returning it this is how the function is going to return now we need our GRE function or component all right uh initially it's going to take a prompt called as name and it's going to just re uh welcome it hello the name now what we're going to do we'll call our higher order component which will be stored in this variable called as enhanced greet we're going to call H and we'll pass greet in this H and we'll export it now in the app.
js component we need to remove that in the app. js component we'll call our enhanced greet and we'll pass in a name as say John all right we have done some error this is H all right and if I were to go to my console you can see the modifying this function with new prompts which means our higher order function is able to take this function and modify it and return you the output so that's all for this question let's move on to our next question which is explain the concept of reconciliation in react now reconciliation is like a process in react when it's like what happens in the background when a particular component is updated and how the virtual domor and the original dor is working together to display the content in the user interface let's look at them one by one there are obviously different phases for this the first part is the initial render that is when a component is first rendered when it's first rendered it's react actually creates a virtual Dom to check what has changed in your code and whatever changes have been made only those certain Elements which you have changed in your code will be reflected in your original Dom only those components will be rendered the other components will not be rendered as no change was made to those components next you have state or props change now when a state or a props change react creates a new virtual Dom every single time a new virtual dor is created because it's a lightweight copy of the original domor so it doesn't take a lot of effort or a lot of it doesn't create a lot of performance optimization issues so every single time you render the component a new virtual domor is created which checks whatever changes have been made and updates accordingly next you have diffing now diffing is basically the comparing part is called as diffing or maybe the difference between the both of them the original Dom and the virtual Dom that is called as diffing next you have the updating the Dom part whatever changes are there in the virtual Dom because of the changes in the code that you made only those things will be changed in the original Dom as well that is called as updating the Dom next you have committing phase that is whatever changes were made rolling them out and committing them to the original domor is called as committing phase finally react commits that changes to the actual D moving on to our next question how do react portals work and when should they be used um react portal is a way to render a components of children into different parts of the Dom outside the parent components hierarchy while maintaining the react code component structure I'll tell you this means now react portal is basically when you need to create a particular component like maybe a modal or something like a popup you must have seen popups when you're trying to use websites and Sunday there's a popup about some advertisement or something that thing that particular div element or that particular element that is created using react portals let me show you how that is called as a modal let me show you how that is created so we need to create a modal component it's going to have two prompts which will be is open which will make sure that it's visible or if it's hidden it will decide if it should be visible or it should be hidden and then the children now um if the portal is not open not open then we don't need to do anything so just return null however if it is open then we'll call react Dom we need to import react we're going to create a portal here inside of which we're going to call a div and we're going to show the children in here children is basically whatever the components we'll be having inside the modal um we'll need to style it a little this is going to be a bit hard now inline styles are always hard but top is say 50 [Music] pixel left is say 50% transform translate 50 percentage percentage color let's put it as white background color let's put it as purple what else do we need padding 20 pixels we might need okay let's not add box Shadow we'll have only this much and it should be shown in document. body all right okay we have everything now let's try to import it in our app JS let's remove that we need oh my God okay okay and we need you state here so in here is modal open and set is modal open to control their states it will be a Boolean value so let's start with the false and we have an H1 welcome to react portal and we need to add two buttons here which will be the open mo open modal and the close modal so when you click on open modal we're going to set is open modal to true and when you click on close modal this will be closed and it will become false let's see how that came out so if I click on open modal nothing's happening we did something wrong let's see what we did wrong we did not call modal we were supposed to call modal uh will set is open as is modal open we'll just add this is IM modal and the close one should be inside of this now let's see all right create portal is not a function oh okay this is not this is react Dom okay this is the modal and we can close it and that is basically how react portals work so let's move on to our next question how does react router handle navigation in a single page now react in a single page application react router is used to handle navigation between different usser pages without the need to reload the entire page now what router or this navigation does is that you don't have to go around and have different IP addresses for everything instead everything happens inside a single page and you can navigate to different pages like your homepage about page about uh contact us page all of these let me just quickly show you how to integrate it into your react application now before you do this make sure to install your react router do so while that's happening in the background let me just go to my app.