24
My Top React Interview Questions
This article summarizes a list of React interview questions that I would ask candidates and that I get often asked in interviews.
- 1. What is React?
- 2. What are the advantages of React?
- 3. What are disadvantages of React?
- 4. What is JSX?
- 5. How to pass data between components?
- 6. What are the differences between functional and class components?
- 7. What is the Virtual DOM?
- 8. Is the Shadow DOM the same as the Virtual DOM?
- 9. What is “React Fiber”?
- 10. How does state differ from props?
- 11. What are the differences between controlled and uncontrolled components?
- 12. What are the different lifecycle methods in React?
- 13. How can you improve your React app’s performance?
- 14. What are keys in React?
- 15. What are Higher Order Components?
- 16. What are error boundaries?
- 17. Why Hooks were introduced?
- 18. What is the purpose of useEffect hook?
- 19. What are synthetic events in React?
- 20. What is the use of refs?
- Conclusion
It’s the V in the MVC (Model - View -Controller), so it is rather an open-source UI library than a framework.
- Good performance: due to VDOM, see #17.
- Easy to learn: with basic JavaScript knowledge you can start building applications. Frameworks like Angular require more knowledge about other technologies and patterns like RxJS, TypeScript, and Dependency Injection.
- One-way data flow: this flow is also called “parent to child” or “top to bottom” and prevents errors and facilitates debugging.
- Reusable components: Re-using React components in other parts of the code or even in different projects can be done with little or no changes.
- Huge community: The community supplies a ton of libraries that can be used to build React applications.
- It is very popular among developers.
- As React provides only the View part of the MVC model you mostly will rely on other technologies in your projects as well. Therefore, every React project might look quite different.
- Some people think that JSX is too difficult to grasp and too complex.
- Often poor documentation for React and its libraries.
JSX (JavaScript XML) allows us to write HTML inside JavaScript. The official docs describe it as “syntax extension to JavaScript”.
React recommends using JSX, but it is also possible to create applications without using JSX at all.
A simple JSX example:
const element = <h1>Hello, world!</h1>;
- Use props to pass data from parent to child.
- Use callbacks to pass data from child to parent.
- Use any of the following methods to pass data among siblings:
- Integrating the methods mentioned above.
- Using Redux.
- Utilizing React’s Context API.
So let’s take a look at the differences:
Functional components are JavaScript functions and therefore can be declared using an arrow function or the function
keyword. Props are simply function arguments and can be directly used inside JSX:
const Card = (props) => {
return(
<h2>Title: {props.title}</h2>
)
}
function Card(props){
return(
<h2>Title: {props.title}</h2>
)
}
Class components are declared using the ES6 class
keyword. Props need to be accessed using the this
keyword:
class Card extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<h2>Title: {this.props.title}</h2>
)
}
}
In functional components we need to use the useState
hook to be able to handle state:
const Counter = (props) => {
const [counter, setCounter] = useState(0);
const increment = () => {
setCounter(++counter);
}
return (
<div>
<p>Count: {counter}</p>
<button onClick={increment}>Increment Counter</button>
</div>
)
}
It’s not possible to use React Hooks inside class components, therefore state handling is done differently in a class component:
class Counter extends React.Component {
constructor(props){
super(props);
this.state = {counter : 0};
this.increment = this.increment.bind(this);
}
increment {
this.setState((prevState) => {
return {counter: prevState.counter++};
});
}
render() {
return (
<div>
<p>Count: {this.state.counter}</p>
<button onClick={this.increment}>Increment Counter</button>
</div>
)
}
}
The Virtual DOM (VDOM) is a lightweight JavaScript object and it contains a copy of the real DOM.
Real DOM | Virtual DOM |
---|---|
Slow & expensive DOM manipulation | Fast & inexpensive DOM manipulation |
Allows direct updates from HTML | It cannot be used to update HTML directly |
Wastes too much memory | Less memory consumption |
No, they are different.
The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components.
The virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
Fiber is the new reconciliation engine in React 16.
Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.
Both props and state are plain JavaScript objects.
Props (short for “properties”) is an object of arbitrary inputs that are passed to a component by its parent component.
State are variables that are initialized and managed by the component and change over the lifetime of a specific instance of this component.
The value of an input element in a controlled React component is controlled by React.
The value of an input element in an uncontrolled React component is controlled by the DOM.
React class components provide these lifecycle methods:
-
componentDidMount()
: Runs after the component output has been rendered to the DOM. -
componentDidUpdate()
: Runs immediately after updating occurs. -
componentWillUnmount()
: Runs after the component is unmounted from the DOM and is used to clear up the memory space.
There exist some other rarely used and legacy lifecycle methods.
Hooks are used in functional components instead of the above-mentioned lifecycle methods. The Effect Hook useEffect
adds, for example, the ability to perform side effects and provides the same functionality as componentDidMount
, componentDidUpdate
, and componentWillUnmount
.
- Use React.PureComponent which is a base class like
React.Component
but it provides in some cases a performance boost if itsrender()
function renders the same result given the same props and state. - Use useMemo Hook to memoize functions that perform expensive calculations on every render. It will only recompute the memoized value if one of the dependencies (that are passed to the Hook) has changed.
- State colocation is a process that moves the state as close to where you need it. Some React applications have a lot of unnecessary state in their parent component which makes the code harder to maintain and leads to a lot of unnecessary re-renders. This article provides a detailed explanation about state colocation.
- Lazy load your components to reduce the load time of your application. React Suspense can be used to lazy load components.
React needs keys to be able to identify which elements were changed, added, or removed. Each item in an array needs to have a key that provides a stable identity.
It’s not recommended to use indexes for keys if the order of items may change as it can have a negative impact on the performance and may cause state issues. React will use indexes as keys if you do not assign an explicit key to list items.
Check out Robin Pokorny’s article for an in-depth explanation of the negative impacts of using an index as a key. Here is another in-depth explanation about why keys are necessary if you’re interested in learning more.
A higher-order component (HOC) is a function that takes a component and returns a new component.
They are an advanced technique in React for reusing component logic and they are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature:
const EnhancedComponent = higherOrderComponent(WrappedComponent);
Whereas a component transforms props into UI, a higher-order component transforms a component into another component.
React 16 introduced a new concept of an “error boundary”.
Hooks solve a wide variety of seemingly unconnected problems in React that were encountered by Facebook over five years of writing and maintaining tens of thousands of components:
- Hooks allow you to reuse stateful logic without changing your component hierarchy.
- Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data).
- Hooks let you use more of React’s features without classes.
- It removed the complexity of dealing with the
this
keyword inside class components.
The Effect hook lets us perform side effects in functional components. It helps us to avoid redundant code in different lifecycle methods of a class component. It helps to group related code.
A Ref is a special attribute that can be attached to any component. It can be an object created by React.createRef()
, a callback function or a string (in legacy API).
To get direct access to a DOM element or component instance you can use ref attribute as a callback function. The function receives the underlying DOM element or class instance (depending on the type of element) as its argument.
In most cases, refs should be used sparingly.
I hope this list of React interview questions will help you to get your next React position. Leave me a comment if you know any other important React interview questions.
If you liked this article, follow me on Twitter to get notified about new blog posts and more content from me.
If you are looking for more interview questions you should take a look at this list of top 500 React interview questions & answers.
24