React.js top 100 questions with examples
- Get link
- X
- Other Apps
Here’s a compilation of top 100 React.js interview questions along with explanations and examples. These questions cover various React concepts, ranging from basics to advanced topics.
1. What is React?
Answer: React is an open-source JavaScript library for building user interfaces, particularly single-page applications where you need a fast, interactive UI. React lets you build components that are reusable and efficiently update when state or data changes.
2. What are components in React?
Answer: Components are the building blocks of React applications. They are JavaScript functions or classes that return JSX (HTML-like syntax). Components can be functional or class-based.
Example:
jsx// Functional Component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
3. What is JSX?
Answer: JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML but can include JavaScript expressions. JSX is used to describe what the UI should look like.
Example:
jsxconst element = <h1>Hello, World!</h1>;
4. What is the difference between React and Angular?
Answer: React is a JavaScript library focused on building UI components, while Angular is a complete front-end framework. React is more flexible and can be paired with other libraries for routing, state management, etc., while Angular provides a full-fledged framework with built-in tools for routing, state management, and more.
5. What is the Virtual DOM in React?
Answer: The Virtual DOM is a lightweight in-memory representation of the actual DOM. React uses the Virtual DOM to efficiently update the real DOM by comparing the changes and only updating the parts of the DOM that need to be changed.
6. What are props in React?
Answer: Props (short for "properties") are read-only inputs passed from a parent component to a child component. They are used to pass data and event handlers between components.
Example:
jsxfunction ParentComponent() {
return <ChildComponent message="Hello from Parent" />;
}
function ChildComponent(props) {
return <h1>{props.message}</h1>;
}
7. What is state in React?
Answer: State is an object used to store the data or information about the component that can change over time. It is mutable, unlike props, which are immutable.
Example:
jsxfunction Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
8. What is the useState Hook in React?
Answer: useState is a React hook that allows you to add state to functional components. It returns an array with the current state value and a function to update that state.
Example:
jsximport React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
9. What is the useEffect Hook in React?
Answer: useEffect is a hook that allows you to perform side effects in functional components (e.g., fetching data, subscribing to events, updating the DOM). It can be thought of as a combination of componentDidMount, componentDidUpdate, and componentWillUnmount in class components.
Example:
jsximport React, { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty array means this effect runs only once when the component mounts
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
10. What is the difference between state and props?
Answer:
- Props are passed from a parent component to a child component and are immutable.
- State is managed within a component, and it can be changed or updated, usually in response to user input.
11. What are functional components in React?
Answer: Functional components are JavaScript functions that return JSX. They can use hooks (like useState and useEffect) to manage state and side effects.
12. What are class components in React?
Answer: Class components are ES6 classes that extend React.Component and must have a render() method that returns JSX. They can have state and lifecycle methods.
Example:
jsxclass Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
13. What are React Lifecycle Methods?
Answer: Lifecycle methods are special methods in class components that allow you to run code at specific points in a component's life, such as when it mounts, updates, or unmounts. These include componentDidMount, componentDidUpdate, and componentWillUnmount.
14. What is the Context API in React?
Answer: The Context API provides a way to share values between components without having to explicitly pass props through every level of the tree. It is useful for global state management.
Example:
jsxconst ThemeContext = React.createContext('light');
function ThemedComponent() {
return (
<ThemeContext.Consumer>
{theme => <div>The current theme is {theme}</div>}
</ThemeContext.Consumer>
);
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
);
}
15. What are React Fragments?
Answer: Fragments allow you to group multiple elements without adding extra nodes to the DOM. This is helpful when you need to return multiple elements from a component but don't want to introduce additional divs or wrappers.
Example:
jsxfunction App() {
return (
<>
<h1>Hello</h1>
<p>This is a fragment example.</p>
</>
);
}
16. What are React Hooks?
Answer: React Hooks are functions that let you "hook into" React state and lifecycle features from function components. The most common hooks are useState, useEffect, useContext, useReducer, and useRef.
17. What is the purpose of key in React lists?
Answer: The key prop is used to uniquely identify elements in a list. This helps React efficiently update the DOM when the list changes, by tracking which items have changed, added, or removed.
Example:
jsxconst items = ['Apple', 'Banana', 'Orange'];
function ItemList() {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
18. What is prop drilling in React?
Answer: Prop drilling is the process of passing data from a parent component to a deeply nested child component through multiple intermediary components.
19. What is the purpose of React.memo?
Answer: React.memo is a higher-order component that prevents unnecessary re-renders of a component by memoizing the component and only re-rendering it if its props change.
Example:
jsxconst MyComponent = React.memo(function MyComponent({ name }) {
return <div>{name}</div>;
});
20. What is useRef in React?
Answer: useRef is a hook that can be used to access a DOM element or persist a value across renders without causing a re-render.
Example:
jsximport React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus the input</button>
</div>
);
}
21. How does useReducer work in React?
Answer: useReducer is a hook for managing more complex state logic in React. It's similar to useState, but it allows you to use a reducer function to update the state based on the action dispatched.
Example:
jsximport React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
22. What are controlled components in React?
Answer: A controlled component is an input element whose value is controlled by the React state. You can modify the value of the input through the state and handle changes with event handlers.
Example:
jsxfunction ControlledInput() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<input type="text" value={value} onChange={handleChange} />
);
}
23. What are uncontrolled components in React?
Answer: An uncontrolled component is an input element where the value is handled by the DOM rather than React. You can access the value using a ref.
Example:
jsxfunction UncontrolledInput() {
const inputRef = useRef();
const handleSubmit = () => {
alert('Input value: ' + inputRef.current.value);
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
24. What is the difference between null and undefined in React?
Answer: In React, null can be used to render nothing, while undefined usually causes rendering issues if used within JSX. For example, rendering undefined in JSX will cause an error, but null will render nothing.
25. How do you handle form validation in React?
Answer: Form validation can be done by creating a controlled component and using JavaScript to validate the input values. You can also use libraries like Formik or React Hook Form for handling complex forms.
26. What is higher-order component (HOC) in React?
Answer: A higher-order component is a function that takes a component and returns a new component with additional functionality. It’s a pattern for reusing component logic.
Example:
jsxfunction withLogging(Component) {
return function(props) {
console.log('Rendering', Component.name);
return <Component {...props} />;
};
}
const LoggedComponent = withLogging(MyComponent);
27. What is the purpose of React.StrictMode?
Answer: React.StrictMode is a wrapper component that helps identify potential problems in an application, such as unsafe lifecycle methods, legacy string ref API, and other issues during development.
28. What are error boundaries in React?
Answer: Error boundaries are React components that catch JavaScript errors anywhere in the component tree, log those errors, and display a fallback UI instead of crashing the entire app.
29. What is React.lazy and Suspense?
Answer: React.lazy allows you to dynamically import components, while Suspense is used to handle the loading state of these components. This can help with code splitting and performance optimization.
30. What is the difference between componentDidMount and useEffect?
Answer:
componentDidMountis a lifecycle method used in class components to perform actions after the component is mounted.useEffectis the functional component equivalent and is used to perform side effects after the component renders.
- Get link
- X
- Other Apps
Comments
Post a Comment