React.js has become one of the most popular front-end libraries for building user interfaces, and with that popularity comes the need for developers to understand its nuances. Preparing for a React.js interview can be a difficult task. In this article, we’ll go over 20 common React.js interview questions and answers to help you ace your interview.
1. What is React?
Answer:
React is a JavaScript library developed by Facebook for building user interfaces, particularly single-page applications (SPAs). It allows developers to create reusable UI components, making the code more modular and easier to manage.
Example:
Imagine a webpage with multiple buttons that need to change color on click. Instead of writing separate functions for each button, you can create a single Button component in React and reuse it with different props.
2. What are components in React?
Answer:
Components are the building blocks of a React application. They are reusable pieces of code that represent a part of the UI. Each component can manage its own state and props, allowing for a dynamic user interface.
Example:
const Button = ({ label, onClick }) => {
return <button onClick={onClick}>{label}</button>;
};
3. What is the difference between state and props?
Answer:
- State is a local data store that is managed within a component. It can change over time, often in response to user actions.
- Props (short for properties) are read-only attributes passed from a parent component to a child component. Props cannot be modified by the child.
Example:
const Counter = () => {
const [count, setCount] = React.useState(0); // State
return (
<div>
<h1>{count}</h1>
<Button label="Increment" onClick={() => setCount(count + 1)} />
</div>
);
};
4. What is the Virtual DOM?
Answer:
The Virtual DOM is a lightweight copy of the actual DOM. React uses the Virtual DOM to optimize updates. When a component’s state changes, React updates the Virtual DOM first, then compares it to the actual DOM and only updates the parts that have changed. This process, known as reconciliation, improves performance.
5. What are hooks in React?
Answer:
Hooks are special functions that let you “hook into” React features, like state and lifecycle methods, without writing a class. The most common hooks are useState
and useEffect
.
Example:
import React, { useState, useEffect } from 'react';
const Timer = () => {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => setCount(prevCount => prevCount + 1), 1000);
return () => clearInterval(timer); // Cleanup on unmount
}, []);
return <h1>{count}</h1>;
};
6. What is JSX?
Answer:
JSX is a syntax extension for JavaScript that allows you to write HTML elements in your JavaScript code. It makes it easier to visualize the UI structure. Under the hood, JSX gets compiled to JavaScript function calls.
Example:
const element = <h1>Hello, World!</h1>; // JSX
const element = React.createElement('h1', null, 'Hello, World!'); // JavaScript
7. Explain the useEffect Hook.
Answer:
The useEffect
hook allows you to perform side effects in function components, such as fetching data, subscribing to events, or directly manipulating the DOM. It runs after every render by default but can be customized to run only when certain values change.
Example:
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
};
fetchData();
}, []); // Runs once on mount
8. What is a higher-order component (HOC)?
Answer:
A higher-order component is a function that takes a component and returns a new component. HOCs are used to share common functionality between components without repeating code.
Example:
const withLoading = (WrappedComponent) => {
return (props) => {
return props.isLoading ? <h1>Loading...</h1> : <WrappedComponent {...props} />;
};
};
9. What are controlled and uncontrolled components?
Answer:
- Controlled components are those whose form data is handled by the component’s state.
- Uncontrolled components store their own state internally and can be accessed via refs.
Example of a Controlled Component:
const Form = () => {
const [value, setValue] = useState('');
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
};
10. What is the purpose of keys in React?
Answer:
Keys help React identify which items have changed, are added, or are removed. This identification allows React to optimize rendering and improves performance. Keys should be unique among siblings.
Example:
const listItems = items.map(item => <li key={item.id}>{item.name}</li>);
11. What is Context API?
Answer:
The Context API provides a way to pass data through the component tree without having to pass props down manually at every level. It’s useful for global data like themes or user authentication.
Example:
const ThemeContext = React.createContext('light');
const App = () => {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
};
const Toolbar = () => {
return <ThemedButton />;
};
const ThemedButton = () => {
const theme = React.useContext(ThemeContext);
return <button className={theme}>I am styled by theme context!</button>;
};
12. Explain the difference between class components and functional components.
Answer:
- Class components are ES6 classes that extend from
React.Component
and have lifecycle methods. - Functional components are simpler and are just JavaScript functions. With hooks, they can now manage state and side effects, making them more versatile.
Example of a Functional Component:
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;
13. What is Redux?
Answer:
Redux is a state management library for JavaScript applications. It provides a centralized store for managing the application state and allows for predictable state updates through actions and reducers. It’s commonly used with React but can work with any UI library.
14. How can you optimize a React application’s performance?
Answer:
You can optimize performance in several ways:
- Use
React.memo
to prevent unnecessary re-renders. - Implement code splitting with React.lazy and Suspense.
- Use the useCallback and useMemo hooks to memoize functions and values.
- Keep the component tree shallow.
15. What are fragments in React?
Answer:
Fragments are a way to group a list of children without adding extra nodes to the DOM. This is useful when returning multiple elements from a component without wrapping them in an additional div.
Example:
const List = () => (
<>
<li>Item 1</li>
<li>Item 2</li>
</>
);
16. What is the significance of the key
prop in React lists?
Answer:
The key
prop is used to give React elements a unique identity. This helps React efficiently update and re-render elements in a list when changes occur.
17. How do you handle forms in React?
Answer:
Forms in React can be managed using controlled components, where the form input values are stored in the component’s state. You can then handle form submissions by defining a function that processes the data.
Example:
const MyForm = () => {
const [inputValue, setInputValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
};
18. What is prop drilling, and how can you avoid it?
Answer:
Prop drilling refers to the process of passing data from a parent component down to child components, even if some of those intermediate components don’t need the data. This can make your component tree cumbersome.
You can avoid prop drilling by using the Context API or state management libraries like Redux.
19. Explain the purpose of the useReducer
hook.
Answer:
The useReducer
hook is an alternative to useState
for managing more complex state logic in React. It is similar to Redux but used within a single component. It’s particularly useful for handling state that depends on previous states or for managing multiple pieces of related state.
Example:
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
};
20. What is React Router, and why is it useful?
Answer:
React Router is a library for routing in React applications. It enables navigation among different components without refreshing the page, making it essential for building single-page applications. It allows you to define routes for different components and handle dynamic routing.
Example:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const App = () => (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
Conclusion
Preparing for a React.js interview can feel overwhelming, but understanding these common questions and their answers can significantly boost your confidence. Focus on not just memorizing the answers but understanding the concepts behind them. Good luck with your interview!