React Interview Questions and Answers
1. What is React, and why is it popular?
Answer:
React is an open-source JavaScript library developed by
Facebook for building user interfaces, particularly single-page applications
(SPAs). It is popular because:
- It uses a virtual DOM for efficient updates and rendering.
- It promotes component-based architecture, making code
reusable and maintainable.
- It has a strong ecosystem with tools like React Router,
Redux, and Next.js.
- It is supported by a large community and is widely used in
the industry.
2. Explain the difference between functional and class
components in React.
Answer:
- Functional Components:
- Written as JavaScript functions.
- Use hooks (like `useState`, `useEffect`) to manage
state and lifecycle methods.
- Simpler and easier to test.
- Example:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
- Class Components:
- Written as ES6 classes.
- Use `this.state` and lifecycle methods like `componentDidMount`.
- More verbose and complex.
- Example:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
3. What are React hooks? Can you name a few commonly used
hooks?
Answer:
React hooks are functions that allow functional components
to use state and lifecycle features. Commonly used hooks include:
- `useState`: Manages state in functional components.
- `useEffect`: Handles side effects like data fetching or
DOM manipulation.
- `useContext`: Accesses context values without prop
drilling.
- `useReducer`: Manages complex state logic.
- `useRef`: Creates mutable references to DOM elements or
values.
Example of `useState`:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() =>
setCount(count + 1)}>Click me</button>
</div>
);
}
4. What is the virtual DOM, and how does it improve
performance?
Answer:
The virtual DOM is a lightweight copy of the actual DOM.
React uses it to optimize rendering:
- When state or props change, React creates a new virtual
DOM tree.
- It compares the new virtual DOM with the previous one (a
process called reconciliation).
- Only the differences (or "diffs") are updated in
the actual DOM, reducing unnecessary re-renders and improving performance.
5. How do you handle forms in React?
Answer:
Forms in React can be handled using controlled components or
uncontrolled components:
- Controlled Components:
- Form data is managed by React state.
- Example:
function Form() {
const [value, setValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(value);
};
return (
<form
onSubmit={handleSubmit}>
<input
type="text"
value={value}
onChange={(e)
=> setValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
- Uncontrolled Components:
- Form data is handled by the DOM itself using `ref`.
- Example:
function Form() {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log(inputRef.current.value);
};
return (
<form
onSubmit={handleSubmit}>
<input type="text"
ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}
6. What is prop drilling, and how can you avoid it?
Answer:
Prop drilling occurs when props are passed through multiple
levels of components, even if intermediate components don't use them. This can
make the code harder to maintain.
To avoid prop drilling:
- Use Context API to share data across components.
- Use state management libraries like Redux or Recoil.
Example of Context API:
const UserContext = React.createContext();
function App() {
return (
<UserContext.Provider value="Amit">
<Component />
</UserContext.Provider>
);
}
function Component() {
const user = useContext(UserContext);
return <h1>Hello, {user}!</h1>;
}
7. What are keys in React, and why are they important?
Answer:
Keys are special attributes used to identify which items
have changed, been added, or been removed in a list. They help React
efficiently update the UI by minimizing re-renders.
Example:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>{number}</li>
);
8. How do you optimize performance in React applications?
Answer:
Performance optimization techniques in React include:
- Using React.memo to memoize functional components.
- Using useCallback and useMemo to memoize functions and
values.
- Implementing code splitting with tools like React.lazy and
Suspense.
- Optimizing re-renders by avoiding unnecessary state
updates.
- Using production builds for deployment.
9. What is Redux, and how does it work with React?
Answer:
Redux is a state management library for JavaScript
applications. It works with React by:
- Storing the entire application state in a single store.
- Using actions to describe state changes.
- Using reducers to specify how the state changes in
response to actions.
- Connecting React components to the Redux store using the `useSelector`
and `useDispatch` hooks.
10. How do you handle routing in React?
Answer:
Routing in React is handled using libraries like React
Router.
Example:
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home
/>} />
<Route path="/about"
element={<About />} />
</Routes>
</Router>
);
}
11. How do you integrate Tailwind CSS with React?
Answer:
To integrate Tailwind CSS with React:
1. Install Tailwind CSS:
npm install tailwindcss
2. Configure Tailwind by creating a `tailwind.config.js`
file.
3. Include Tailwind in your CSS file:
@tailwind base;
@tailwind components;
@tailwind utilities;
4. Use Tailwind classes directly in your JSX:
<button className="bg-blue-500
text-white p-2 rounded">Click Me</button>
12. How do you ensure responsiveness in React applications?
Answer:
To ensure responsiveness:
- Use CSS frameworks like Tailwind CSS or Bootstrap.
- Use media queries for custom responsive designs.
- Test applications on multiple devices and screen sizes.
- Use tools like Chrome DevTools to simulate different
screen sizes.
13. How do you handle API calls in React?
Answer:
API calls can be handled using:
- The `fetch` API or libraries like Axios.
- The `useEffect` hook to trigger API calls on component
mount or state change.
- Example:
useEffect(() => {
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data));
}, []);
0 Comments