ReactJS Interview Questions (Part 1)
Some ReactJS Interview Question which I've been asked
Hi, it's me again. It's been a while since my last post. I've been a little bit busy these days. I've been through some interviews for a front-end position (ReactJS). I want to share with you guys the experiences and some questions that I was asked during the interview. Okay, let's get started A little bit about my background, I've been working as a front-end developer for more than one year. Before, I was very confident about my knowledge of front-end development. After quitting my job at my old company, I started to seek new challenges from other companies. Luckily, I got some interviews from some companies. Some are bad, and some are good. But I gain much experience after that. Here are some questions I was asked:
There are 2 ways, they are a functional component and a class component. Nowadays, with the birth of "React Hook", the functional component is more and more popular among ReactJS developers. I think that most of the company will choose functional over a class component.
- The first reason is that functional components are easier to read, debug and test. In my opinion, class components are sometimes too bulky. "The more code you write, the more bug you will get". It's a joke from my leader, but I think it's partially true. The functional component offers us a very clean way to write code and fewer lines of code.
- The second reason is that, without using the class component, we can get rid of the "this" keyword. I think that understanding how "this" keyword works in JS is a tricky part, if you use a class component you have to stick with it (of course arrow functions sometimes can help you but in some cases, they can't)
- Get rid of complex life cycle methods. Everyone who starts to learn ReactJS must know about the life cycle methods. In the class component, we have so many life cycle methods and some of them are rarely used. In the functional component, the life cycle is much easier
- Custom Hooks: A very powerful feature is that you can write custom hooks and "hook" into your component. A custom hook is a component that consists of common states, and functions that you want to share among some different components. It's extremely powerful and it's the main reason that made me switch from class component to functional component.
Lifecycle methods as the series of events that happen from the birth of a React component to its death.
Every component in React goes through 3 phases, they are:
The constructor for a React component is called before it is mounted
When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement
Typically, in React constructors are only used for two purposes:
- Initializing local state by assigning an object to
this.state. - Binding event handle methods to an instance.
getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates
The render() method is the only required method in a class component.
Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases, you should rely on the default behavior.
shouldComponentUpdate() is invoked before rendering when new props or states are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.
getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions created in componentDidMount().
- useMemo memorizes a value
- useCallback memorizes a callback
- useCallback returns its function uncalled and calls it after while useMemo calls its function immediately and returns the result.
- useCallback(fn, deps) is equivalent to useMemo(() ⇒ fn, deps)
- Use useMemo and useCallback when you want to prevent re-rendering children components
- Returned value of useMemo and function of useCallback are stored and only deleted when program stops.
Virtual DOM is just a representation of the Real DOM in the form of javascript objects. It is just a tree data structure of plain javascript objects that exists in the memory
Before diving into the answer (actually, it's just my answer, I've been searching for the best answer to this question for a while and haven't found out yet, up until this point, in my opinion, it's the best answer I would tell).
Firstly, many people say that "React uses Virtual DOM because it's faster than real DOM. The most 2 common arguments for this point are:
- It updates ONLY those elements that need to be updated (using diff).
- It batches the updates and hence we update the real DOM only a single time. Thus the repainting is also done only once which otherwise would have been done multiple times.
But I think it's not true because:
- As far as I know, all modern browsers are efficient enough to update only the required elements in the DOM. For example, if I have two 'p' tags and I change the text in one of the p tags using a button click, then only that p tag will be updated by safari (I have verified this using paint flashing). So how is point 1 an advantage if it is already being implemented by the browsers?
- How exactly does React batch the updates? Eventually React will also have to use the DOM API to update the real DOM. So why is it that if we directly use the DOM API then the changes will not be batched whereas when React uses it then they are batched?
Okay, I'll answer those questions one by one.
For the first question.
The reason why React has to use Virtual DOM is the way it renders the component. Every time the component changes its state, instead of updating that state and updating the part which uses that state in HTML, React chooses to re-render the UI entirely. We all know that updating the entire DOM is very expensive which can cause low performance. So there must be another way to solve this, and yeah, it's when Virtual DOM comes into play. A Virtual DOM is just a representation of the Real DOM in the form of javascript objects. It is just a tree data structure of plain javascript objects that exists in the memory. As compared to the Real DOM, rendering of the Virtual DOM is much faster because it is never rendered on the screen (no reflow or repainting needs to be done).
So how does the Virtual DOM solve the problem? When we load our app, React creates a Virtual DOM that is an exact virtual copy of the Real DOM. Whenever there is a state change in a component, instead of re-rendering the entire Real DOM, React renders an entirely new Virtual DOM (with the updated state). Then it does a diff between the old Virtual DOM (the initial copy of the Real DOM) and this new Virtual DOM (rendered after state change) to find out the changes between them and it does ONLY those changes in the Real DOM. In this way, the entire UI is re-rendered (by rendering an entirely new Virtual DOM) but only the minimum required changes are done in the real DOM.
So point #1 above is just a part of the main problem React wants to solve - they want to re-render the entire UI from scratch, and somehow it became an argument when people talk about the benefit of Virtual DOM over real DOM. (But IMO, it's not an advantage I would say).
As for the second point, React makes batching easier for us.
In React, while the reads are done on the Real DOM, the writes (state changes) are not done on the Real DOM. Instead, the writers are queued. Then when all our reads and writes have been processed, a new Virtual DOM is built based on the writes. Then diffing is done between the old and new Virtual DOM and then React writes the required changes to the Real DOM to update it. Hence eventually all the writes on the Real DOM are done together in a single reflow.
Sum up:
React use Virtual DOM because Virtual DOM helps React solve its problem - re-rendering the entire UI from scratch.
Virtual DOM is not faster than real DOM, it's just easier.
Redux is a "state management" library that helps React solve the prop drilling problem. In the beginning, Redux is used to avoid passing unnecessary props between components. For example, we have component A and component B, and we want to pass a prop to component B from component A, but between A and B we have components C, D. We assume that C and D don't need the props passed from A, but to deliver props to B, we also have to pass that props to C and D. It's inconvenient, right? But after that, Redux helps us solve a bigger problem, we want to separate logic code and UI. Like we want to group all logic code for processing stuff like calling API, and manipulating data from API,... it's time where Redux shines. Moreover, with Redux, we can debug our app easily because we can know the flow of data and our code with the help of some middleware and extensions.
We all know that context and redux help us solving the prop drilling problem. But they're not the same thing and they have a different concepts.
Context is just a global store for our app while Redux is more than that.
- Use Context over Redux when you just want to avoid passing props through components
- Use Redux over Use Context when you want to avoid context hell, track your state through your app, split logic and actions out of your component, or use middleware like state logging...
One downside of Context is that to avoid unnecessary re-render (because each time the data change, all the consumers of the context provider would be re-render) we have to split our app into multiple contexts which can lead to something called "Context Hell"
Okay, so I've gone through some questions I asked in the interview. Of course, it's not the end because there are tons of other questions, but this post is quite long now so I think I will come back with this series later. Keep it up.
If you have any questions, feel free to inbox me on Facebook or comment down here. Thank you!
Ref:
Stackoverflow: https://stackoverflow.com/questions/61245695/how-exactly-is-reacts-virtual-dom-faster