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.
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>
);
};
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 li
s.
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?
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?
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>;
};
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>
</>
);
};
11. What are portals
in React?
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);
};
Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja
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.
-
I am a beginner, how should I learn Front-End Web Dev?
Look into the following articles: Would you mentor me?
Sorry, I am already under a lot of workload and would not have the time to mentor anyone.
Top comments (17)
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.
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
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.
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.
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.
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?
Agreed.
Cool article tho!
Oh this is so good for beginners! Very concise and well put together ππΌ
Nice compilation, thanks
THX for that.
I appreciate you spending your precious time to write down such lengthy thoughts!
Best!
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.
I'm always wary of people with this attitude. The thing is its hard to find strong engineers. If you are an engineer lacking knowledge in these areas then its possible that you will not be able to contribute at the same level as someone who does. You don't need to use this knowledge day-in-day-out, but when tricky problems come up, you should be able to easily know what options you have for solving them.
To use the same car driver anology. Yes, to be a good driver, you don't need to know the composition of oil. But if your car breaks down, are you going to have the skills to fix it? Or will you need to hire a mechanic? Maybe you can spend 5 hours googling what the car is doing with the oil you are putting in to maybe understand what is going wrong.
Point is, if you are going to use a tool, as an engineer, you can probably go far knowing the bare minimum (how to drive), until you are working on complex systems that rely on the core functionality of those tools; if you don't know anything beyond the bare minimum, there's going to be a limit to how much you can help.
And specifically speaking about React, the react core is REALLY small, so expecting that engineers know many of these topics mentioned in this blog is not outragous.
But even if you don't know the answer to these questions, you should be able to participate in a conversation about these things, which is what the interviews should be ultimately. If you see these questions as a red flag, honestly I think you as a candidate are a red flag -- it just shows that have no interest in having a deep understanding of the tools you use daily, and/or you are not a great communicator (not able to have conversations about things you don't know about). I'm not speaking in behalf of all interviewers here, but myself, as someone who carries out interviews as a conversation more so than a test.
Also, In my opinion, the culture of "I'll google it when I need it" leads to many engineers building sub-optimal solutions, (not just in terms of performance, but speaking generally), and many times, code that is coppied-and-pasted from blogs or stack overflow without the author thinking critically about what is needed and not needed for their specific problem. Ultimately this is what interviewing is about for me. Getting indicators that the candidate has the ability to think for himself and solve a problem using (hopefully) a wide range of technical skills in their respective area. And there just isn't a way around that other than making them solve some problems and start conversations about these topics.
Lastly I'll say, the reason why I'm so moved by this is that it does no good to encourage people to not spend the time learning these things. By learning these things, they are able to contribute at a higher-level than someone who doesn't, and can become a better asset for their teams. Is your opinion that this may be a red flag, but in my opinion, it only HELPS to spend time learning these things, if you are planning to work with React daily.
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.
I agree with much of what you said I think I misunderstood your stance. But I didn't appreciate your tone which seemed a bit condescending (at times) π
I agree, interviews should not be carried out like exams with close ended questions, but there's nothing wrong with digging into these topics in an interview. I think its totally fair to ask someone to explain their mental model for understanding what react does, it doesn't have to be a text book definition, but I think its completely reasonable to expect that developers have SOME mental model for what react is doing under the hood, and asking them to explain that is reasonable in my opinion.
Also, on the topic of googling, OBVIOUSLY every engineer googles things, like API documentation, common approaches for a given problem etc. Research is part of the job. But also is internalizing the research and making a decision on what you are going to do. What I was speaking about was about a breed of developers that google then copy and paste solutions without thinking critically about the code they are committing. My opinion (and one of my points) is that this group of developers overlap with the developers that do not take the time to learn the fundamentals of the technologies they work with (like virtual dom, and core react APIs if you work with react). I was projecting an assumption -- I may be wrong, but I've seen this correlation before.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.