DEV Community

Cover image for 11 Advanced React Interview Questions you should absolutely know (with detailed answers)
Tapajyoti Bose
Tapajyoti Bose

Posted on

11 Advanced React Interview Questions you should absolutely know (with detailed answers)

1. What is the React Virtual DOM?

Virtual DOM is a concept where a virtual representation of the real DOM is kept inside the memory and is synced with the actual DOM by a library such as ReactDOM.

The virtual DOM is an object that represents the real DOM in the memory. Since DOM updates are an integral part of any web app but are the costliest operation in the world of frontend, the virtual DOM is utilized to check for parts of the app that need to be updated & update only those parts, thus significantly boosting performance.

2. Why do we need to transpile React code?

React code is written in JSX, but no browser can execute JSX directly as they are built to read-only regular JavaScript.

Thus we require to use tools like Babel to transpile JSX to JavaScript so that the browser can execute it.

transpile

3. What is the significance of keys in React?

Keys in React is used to identify unique VDOM Elements with their corresponding data driving the UI; having them helps React optimize rendering by recycling existing DOM elements.

Key helps React identify which items have changed, are added, or are removed, enabling it to reuse already existing DOM elements, thus providing a performance boost.

For example:

const Todos = ({ todos }) => {
  return (
    <div>
      {todos.map((todo) => (
        <li>{todo.text}</li>
      ))}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

This would cause new DOM Elements to be created everytime todos change, but adding the key prop (<li key={todo.id}>{todo.text}</li>) would result in "dragging" around the DOM Elements inside the ul tag & updating only the necessary lis.

4. What is the significance of refs in React?

Refs are variables that allow you to persist data between renders, just like state variables, but unlike state variables, updating refs does NOT cause the component to re-render.

Refs are usually used to, but not restricted to, store reference to DOM elements.

5. What are the most common approaches for styling a React application?

styling

CSS Classes

React allows class names to be specified for a component like class names are set for a DOM element in HTML.

When developers first start using React after developing traditional web applications, they often opt for CSS classes as they are already familiar with the approach.

Inline CSS

Styling React elements using inline CSS allows styles to be completely scoped to an element. However, certain styling features are not available with inline styles. For example, the styling of pseudo-classes like :hover.

Pre-processors (Sass, Stylus, and Less)

Pre-processors are often used on React projects. This is because, like CSS, they are well understood by developers and are often already in use if React is being integrated into a legacy application.

CSS-in-JS Modules (Styled Components, Emotion, and Styled-jsx)

CSS-in-JS modules are a popular option for styling React applications because they integrate closely with React components. For example, they allow styles to change based on React props at runtime. Also, by default, most of these systems scope all styles to the respective component being styled.

6. What are some of the performance optimization strategies for React?

Using useMemo

useMemo is a React hook that is used for caching CPU-Expensive functions. A CPU-Expensive function called repeatedly due to re-renders of a component, can lead to slow rendering.

useMemo hook can be used to cache such functions. By using useMemo, the CPU-Expensive function gets called only when it is needed.

useCallback can be used to obtain a similar result.

Lazy Loading

Lazy loading is a technique used to reduce the load time of a React app. It helps reduce the risk of web app performances to a minimum, by loading up the components as the user navigates through the app.

7. What is prop drilling and how to avoid it?

prop-drilling

Sometimes while developing React applications, there is a need to pass data from a component that is higher in the hierarchy to a component that is deeply nested. To pass data between such components, we pass props from a source component and keep passing the prop to the next component in the hierarchy till we reach the deeply nested component.

The disadvantage of using prop drilling is that the components that should otherwise be not aware of the data have access to the data, moreover, the code becomes harder to maintain.

Prop drilling can be avoided using the Context API or some form of State Management library.

8. What is the StrictMode component and why would you use it?

<StrictMode /> is a component included with React to provide additional visibility of potential issues in components. Suppose the application is running in development mode. In that case, any issues are logged to the development console, but these warnings are not shown if the application is running in production mode.

Developers use <StrictMode /> to find problems such as deprecated lifecycle methods and legacy patterns, to ensure that all React components follow current best practices.

<StrictMode /> can be applied at any level of an application component hierarchy, which allows it to be adopted incrementally within a codebase.

9. What are synthetic events in React?

Synthetic events combine the response of different browser's native events into one API, ensuring that the events are consistent across different browsers. The application is consistent regardless of the browser it is running in.

const Component = () => {
  const handleClick = (e) => {
    e.preventDefault(); // synthetic event
    console.log("link clicked");
  };

  return <a onClick={(e) => handleClick}>Click me</a>;
};
Enter fullscreen mode Exit fullscreen mode

10. Why is it not advisable to update state directly, but use the setState call?

The conventional way to update state is to use the setState call. Without using it, the user would still be able to modify the state, but it would not update the DOM to reflect the new state.

const Component = () => {
  const [count, setCount] = useState(0);
  // let [count, setCount] = React.useState(0);

  const handleClickUpdate = () => {
    setCount((c) => c + 1);
    // count = count + 1; // will not update the DOM
  };

  return (
    <>
      {count}
      <button onClick={handleClickUpdate}>Click me</button>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

11. What are portals in React?

portal

Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

const Portal = ({ children }) => {
  // NOTE: it is advisable to create a new DOM node for the portal
  const portalRoot = document.getElementById("portal-root");

  return ReactDOM.createPortal(children, portalRoot);
};
Enter fullscreen mode Exit fullscreen mode

Research says, writing down your goals on pen & paper makes you 21% to 39% more likely to achieve them. Check out these notebooks and journals to make the journey of achieving your dreams easier: https://www.amazon.com/Tapajyoti-Bose/e/B09VGDDHRR

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

Follow me on Instagram to check out what I am up to recently.

Follow my blogs for Weekly new Tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

Discussion (16)

Collapse
lukeshiru profile image
Luke Shiru

The title says "you should absolutely know", yet of all the questions one is kinda "important", but not that important, and the rest are more like NTH or not even that. I've done my fair share of interviews for React positions, and trust me, this aren't important. The questions should be focus more on day to day practices. We need to stop doing this kind of "school exam" kind of questions.

My take to every question if you want to know
  1. Is an interview, not a school exam. I don't need you to know answers to questions you can just google.
  2. Is way more important that you know why JSX is useful in the first place, not why is it transpiled (heck, I barely care if you actually know it is transpiled).
  3. If they add key in elements they are mapping, it's great. If they forget about it, is also ok. Is something a linter or a code review will catch, and after a few times they'll never forget about it.
  4. ref is generally a smell. If you're accessing a DOM element directly, is very likely you're doing something wrong. If you don't even know about it, that's almost a good sign.
  5. No mention of CSS Modules (file.module.css)? I mean you mentioned the word "modules" twice, and none of them are actual CSS modules, and from my PoV that should be way higher than inline styles.
  6. Keeping your components stateless, keeping functions outside of the components whenever possible. There are lots of ways of making React more performant, and generally avoiding hooks is way better than using a bunch.
  7. If "prop drilling" is a problem, is more a code smell than anything. You might have to simplify components, create custom hooks and so on. Context or State managers aren't a wildcard to solve bad architecture.
  8. If you know about StrictMode, that's great. If you don't, that's also ok.
  9. Yet another NTH, but not mandatory.
  10. Avoid mutations is at the core of a healthy state in React, so this might be the only question that kinda makes sense, yet I would phrase it as: "Why do you think immutability is so important in React?"
  11. NTH, not mandatory.

If you're interviewing and you see questions like this: Run! Take it as a šŸš© red flag šŸš©. If you're an interviewer, then make questions that actually matter, that actually let you know if that person will enjoy working with you in your project. Asking "What is VDOM", is as useful as asking a car driver what's the composition of oil. Knowing that will not make that person a better driver, and knowing the definition of VDOM will not make a person a better developer. Is a NTH yes, but it isn't something you "should absolutely know".

Cheers!

Collapse
k_penguin_sato profile image
K-Sato

If you're interviewing and you see questions like this: Run! Take it as a šŸš© red flag šŸš©. If you're an interviewer, then make questions that actually matter, that actually let you know if that person will enjoy working with you in your project.

Agreed.

Cool article tho!

Collapse
ruppysuppy profile image
Tapajyoti Bose Author

I appreciate you spending your precious time to write down such lengthy thoughts!

Best!

Collapse
semeano profile image
Pedro Semeano • Edited on

I want to work with this guy! šŸ‘†

I've also done my fair share of technical interviews, and it doesn't matter if they know what a Portal is, because they can always go read the documentation and learn it in a couple of minutes.

Collapse
brense profile image
Rense Bakker

Cooncidentally this is actually a pretty good article for people to get started with React haha.

I'm not sure if I would appreciate being asked these questions in an interview though... Answering these kind of higher level concepts is really difficult in a person-to-person conversation, if there's doubt about the candidates capabilities as a React developer it's better to give them a small assignment to see how they deal with prop drilling or a broken example that they need to fix/optimize by memoizing a value etc...

On the other hand these are also things that can be taught pretty quickly through code reviews, so if a company starts asking these kind of questions it's an indication that they're concerned about the wrong things.

Collapse
optimisedu profile image
optimisedu

That's only shows you know how to to use jsx not why react has implemented the features which it has this results in in dev's not knowing how things work means that when the next major update comes out the Dev in questions performance shall drop

Collapse
brense profile image
Rense Bakker

What exactly are you talking about? Knowing how what things work? Knowing how the virtual dom works does not help you to write better performing code. The virtual dom is encapsulated in the React framework black box which is a black box for a reason. Unless you want to start working at React, there's no reason to increase your knowledge of what the virtual dom is and how it works, thats why you use React, to abstract that complexity for you, so you can focus on implementing business logic in the best way possible.

Thread Thread
optimisedu profile image
optimisedu • Edited on

My examples would be that Understanding how the virtual react stores and updates state has a marked importance for performance accessibility and seo. That is what my main focus is and programming people to spit out JSX has also a recognised issue when it comes to just using libraries on top of dependencies or not considering the issues with purely client side rendering.

I completely agree that it is easy to teach JSX but understanding where and why it has emerged and the practicality of a framework built for Facebook is important and often overlooked. If you are down to using the is odd lib/ dependency and using bootstrap without purging or treeshaking why not just use a cms with plugins. It is often not right package for the job even though it works. You need to understand it quite deeply to make your own reactivity optimal abstraction aside.

For many use cases React has a great community but is very average while WordPress is excellent.

I hope this clarifies my position. A programmer should be able to look at patterns, recognise what they need and have a work flow that removes what they don't another reason I used WordPress as an example.

If the global [you] don't understand why your framework is widely used but just know how than can [you] really claim to be full stack. Coincidentally this has been discussed and dissected here although a quote about javascript in 2008 is quoting a different language the future was predicted unsurprisingly well.

Thread Thread
brense profile image
Rense Bakker

The virtual DOM does not store and update state, React does. those state updates are reflected in the virtual DOM by React and then it decides which parts of the actual DOM need to be rerendered. The exact logic behind this is not relevant for any business logic that I've had to implement in the last 10 years.

A developer needs to recognize what the problem is they're trying to solve. React helps developers to solve a lot of problems that would previously take a lot more effort to solve, which is why it became a popular framework.

Comparing a CMS and a frontend framework is somewhat farfetched... There's good CMSes built on top of React or other modern frontend frameworks also. No need to stick with something archeic like Wordpress. And yes, if you have a simple use-case that doesnt require much custom business logic, you can use a CMS. Knowing how the virtual DOM works has no influence on that decision. The question is: "Is my data model simple enough that I can use a pre-built CMS, or is there so much custom business logic that I require something custom."

Full stack has nothing to do with what framework you use. Full stack is about knowing how to work on both frontend and backend code.

If your goal is to come up with your own framework thats better than React, sure then you can deep dive in how React is actually manipulation the virtual DOM internally. However this is not required knowledge to become a good developer. Knowing how to properly use the tools that you need, is what makes you a good developer. Similarly, a carpenter doesn't need to know what happens internally in a hammer when they use it to whack a nail, they just need to know how to whack properly. Unless the carpenter comes to the conclusion they can't find a proper hammer to do the job and decides to built their own hammer.

Thread Thread
optimisedu profile image
optimisedu • Edited on

To clarify I mean updates as in literally as in FPS, ticks and reconciliation. Your hammer analogy is good, I was not referring to framework*s* though I was referring to React and it is fairly blunt :p. I have a lot of respect for the CRA team and how they have approached things. I will quickly say that a carpenter should know their tools.

Like I said if you have just been programmed in how to use JSX for React are you truly full-stack. Can you add the layers and sometimes complex workaround which are required (for instance when updating legacy versions -- I guess that's a rock to a hammer), or solve a mess of a modal window somebody hashed together years ago because React was the only option.

You need to understand how React works in order to justify using it for a lot of the small SPAs which it has been used for which have literally bloated the internet. I am not saying that React doesn't have use-cases, I am not saying React can't be SEO friendly but largely that is overlooked without additional plugins.

To me it feels like when a CS student first discovers bootstrap. They have a whole library of problems to cut corners and leave all the unnecessary functionality.

We have gone off topic. React is good enough because it is flexible, Solid is fast and considers virtual doms to be bloat, Svelte is loved for intuity and ingenuity, Ruby on Rails has a different kind of battle tested simplicity. Likewise Angular is the full package and extends the dom but is perceived as complex.

A dev wants the right tool for the job and there are plenty of good enough's out there. If you want reactivity from react you need some understanding of the virtual dom implimentation. I have thrown you some edge cases but programming is solving problems through automation and hammering out some JSX which misses a tick isn't that.

This reads like a long rant. There are some excellent devs out there who use react, there are less excellent react devs - I won't say they are unicorns but I will say they are limiting themselves.

Edit - had a quick snoop at some of your answers and liked the one where you are basically agreeing with my overall point

Edit 2 -- On revisit my first post wasn't clear šŸ‘ I hope I have clarified a bit?

Collapse
quantumdev profile image
QuantumInkDev

Oh this is so good for beginners! Very concise and well put together šŸ‘šŸ¼

Collapse
imonem profile image
imonem

Nice compilation, thanks

Collapse
magecoder profile image
Andre Schubert

THX for that.

Collapse
joeattardi profile image
Joe Attardi

Most of these questions are pretty vague and honestly do not seem like "absolutely should know" questions.

Like StrictMode is definitely useful but to consider it a must-know for a React job interview is a little silly IMO.

Collapse
sohaibraza profile image
SohaibRaza

Advanced??? Really. All of these are basic concepts, good for beginners.

Collapse
amirrezaheydari profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
amirreza heydari

Please participate in my latest project, thank you

My Project