Showing 50 question(s)
Answer:
React is an open-source JavaScript library developed by Meta for building fast and interactive user interfaces using reusable components. It follows a component-based architecture and uses a virtual DOM to efficiently update the UI.
Code Example:
import React from 'react';
function App() {
return <h1>Hello React!</h1>;
}
export default App;Answer:
JSX (JavaScript XML) is a syntax extension that allows developers to write HTML-like code inside JavaScript. JSX is transpiled into React.createElement() calls before execution.
Code Example:
const element = <h2>Welcome to React</h2>;Answer:
Functional components are JavaScript functions that return JSX and support Hooks. Class components are ES6 classes that extend React.Component and use lifecycle methods. Functional components are now the recommended approach.
Code Example:
// Functional Component
function Welcome() {
return <h1>Hello!</h1>;
}
// Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello!</h1>;
}
}Answer:
Props (properties) are read-only values passed from a parent component to a child component. They allow components to be reusable and configurable.
Code Example:
function Greeting(props) {
return <h2>Hello {props.name}</h2>;
}
<Greeting name="John" />Answer:
State is a built-in object used to store data that can change over time. Updating the state causes React to re-render the component.
Code Example:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}Answer:
useState is a React Hook that allows functional components to manage state. It returns the current state value and a function to update it.
Code Example:
const [name, setName] = useState('John');
setName('David');Answer:
useEffect is used to perform side effects such as fetching API data, updating the document title, subscribing to events, or setting timers. It runs after the component renders.
Code Example:
import { useEffect } from 'react';
useEffect(() => {
console.log('Component Mounted');
}, []);Answer:
The Virtual DOM is a lightweight copy of the real DOM. React compares the previous Virtual DOM with the updated one and only updates the changed elements in the real DOM, improving performance.
Code Example:
// React automatically updates only
// the changed DOM elements.Answer:
Keys uniquely identify list items, helping React efficiently update, add, or remove elements without re-rendering the entire list.
Code Example:
const users = ['John', 'David'];
<ul>
{users.map((user, index) => (
<li key={index}>{user}</li>
))}
</ul>Answer:
The Context API provides a way to share data such as themes, authentication, or user information across components without passing props through every level of the component tree.
Code Example:
const ThemeContext = React.createContext();
function App() {
return (
<ThemeContext.Provider value="dark">
<Home />
</ThemeContext.Provider>
);
}Answer:
The useRef Hook creates a mutable reference that persists across renders. It is commonly used to access DOM elements or store values that do not trigger a re-render.
Code Example:
import { useRef } from 'react';
function App() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
</>
);
}Answer:
useMemo memoizes expensive calculations and only recomputes the value when its dependencies change, improving performance.
Code Example:
const total = useMemo(() => {
return items.reduce((sum, item) => sum + item.price, 0);
}, [items]);Answer:
useCallback memoizes a function so that the same function instance is reused between renders unless its dependencies change.
Code Example:
const handleClick = useCallback(() => {
console.log('Clicked');
}, []);Answer:
useReducer is a Hook used for managing complex state logic. It works similarly to Redux by using a reducer function and dispatching actions.
Code Example:
const reducer = (state, action) => {
switch(action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, { count: 0 });Answer:
Custom Hooks are reusable JavaScript functions that encapsulate component logic using React Hooks. Their names must begin with "use".
Code Example:
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return { count, increment };
}Answer:
Conditional rendering allows components to display different UI based on conditions using if statements, logical operators, or the ternary operator.
Code Example:
{isLoggedIn
? <Dashboard />
: <Login />
}Answer:
A controlled component is a form element whose value is managed by React state.
Code Example:
const [name, setName] = useState('');
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>Answer:
An uncontrolled component stores form data in the DOM instead of React state. It is typically accessed using useRef.
Code Example:
const inputRef = useRef();
<input ref={inputRef} />
<button onClick={() => alert(inputRef.current.value)}>
Submit
</button>Answer:
React uses camelCase event names such as onClick, onChange, and onSubmit. Event handlers are passed as functions.
Code Example:
function App() {
const handleClick = () => {
alert('Button clicked');
};
return (
<button onClick={handleClick}>
Click Me
</button>
);
}Answer:
Form submission is handled using the onSubmit event. The default browser behavior is prevented using event.preventDefault().
Code Example:
function Login() {
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form Submitted');
};
return (
<form onSubmit={handleSubmit}>
<input type="text" />
<button type="submit">
Login
</button>
</form>
);
}Answer:
React Router is a library used for client-side routing in React applications. It enables navigation between different pages without reloading the browser.
Code Example:
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}Answer:
The Link component is used to navigate between routes without refreshing the page. It replaces the traditional HTML anchor tag for internal navigation.
Code Example:
import { Link } from 'react-router-dom';
<Link to="/about">About</Link>Answer:
useNavigate is a React Router Hook used for programmatic navigation. It allows navigation after events such as form submission or login.
Code Example:
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
const login = () => {
navigate('/dashboard');
};Answer:
The Context API allows data such as themes, authentication, and user information to be shared across components without passing props manually through every level.
Code Example:
const UserContext = React.createContext();Answer:
Context values are consumed using the useContext Hook inside functional components.
Code Example:
const ThemeContext = React.createContext();
function Home() {
const theme = useContext(ThemeContext);
return <h2>{theme}</h2>;
}Answer:
API data is commonly fetched using fetch() or Axios inside useEffect so that the request is executed after the component renders.
Code Example:
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);Answer:
Lifecycle behavior is implemented using the useEffect Hook. It can mimic componentDidMount, componentDidUpdate, and componentWillUnmount.
Code Example:
useEffect(() => {
console.log('Mounted');
return () => {
console.log('Unmounted');
};
}, []);Answer:
React.memo is a higher-order component that prevents unnecessary re-rendering by memoizing a functional component when its props have not changed.
Code Example:
const UserCard = React.memo(function UserCard({ name }) {
return <h2>{name}</h2>;
});Answer:
Error Boundaries are React components that catch JavaScript errors in their child component tree and display a fallback UI instead of crashing the entire application.
Code Example:
class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
console.log(error);
}
render() {
return this.props.children;
}
}Answer:
Lazy loading loads components only when they are needed, reducing the initial bundle size. Suspense displays a fallback UI while the lazy-loaded component is being downloaded.
Code Example:
import React, { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
<Suspense fallback={<p>Loading...</p>}>
<Dashboard />
</Suspense>Answer:
Redux is a predictable state management library for JavaScript applications. It provides a centralized store to manage application state, making state changes predictable and easier to debug in large applications.
Code Example:
import { createStore } from 'redux';
const store = createStore(reducer);
store.dispatch({
type: 'INCREMENT'
});Answer:
Redux Toolkit (RTK) is the official, recommended way to write Redux logic. It simplifies Redux development by reducing boilerplate code and providing utilities such as configureStore() and createSlice().
Code Example:
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => {
state.value++;
}
}
});Answer:
React Portals allow components to render their children into a DOM node outside the parent component hierarchy. They are commonly used for modals, tooltips, and dialogs.
Code Example:
import { createPortal } from 'react-dom';
createPortal(
<Modal />,
document.getElementById('modal-root')
);Answer:
A Higher-Order Component is a function that takes a component as input and returns an enhanced component with additional functionality. HOCs are commonly used for authentication, logging, and code reuse.
Code Example:
function withLogger(Component) {
return function(props) {
console.log('Rendering...');
return <Component {...props} />;
};
}Answer:
Render Props is a pattern where a component receives a function as a prop and uses it to determine what to render. It promotes code reuse without using inheritance.
Code Example:
function MouseTracker({ render }) {
return render({ x: 100, y: 200 });
}
<MouseTracker
render={(mouse) => <h2>{mouse.x}</h2>}
/>Answer:
Fragments let you group multiple elements without adding an extra DOM node. They improve the DOM structure and reduce unnecessary wrapper elements.
Code Example:
function App() {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
}Answer:
React Strict Mode is a development-only feature that helps identify potential problems by highlighting unsafe lifecycle methods, deprecated APIs, and unexpected side effects.
Code Example:
import React from 'react';
<React.StrictMode>
<App />
</React.StrictMode>Answer:
Reconciliation is React's process of comparing the previous Virtual DOM with the updated Virtual DOM to determine the minimum number of changes required in the real DOM.
Code Example:
// React automatically performs
// reconciliation during updates.Answer:
Performance can be improved by using React.memo(), useMemo(), useCallback(), lazy loading, code splitting, virtualization, proper key usage, avoiding unnecessary state updates, and optimizing component rendering.
Code Example:
const UserCard = React.memo(UserCardComponent);
const value = useMemo(() => calculateTotal(items), [items]);
const handleClick = useCallback(() => {}, []);Answer:
Follow component-based architecture, use functional components and Hooks, keep components small and reusable, avoid prop drilling by using Context or Redux when appropriate, use TypeScript if possible, optimize performance, write unit tests, and maintain a consistent folder structure.
Code Example:
src/
├── components/
├── pages/
├── hooks/
├── services/
├── context/
├── store/
└── utils/Answer:
React Testing Library (RTL) is a testing library that focuses on testing React components from the user’s perspective. It encourages testing behavior instead of implementation details.
Code Example:
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders heading', () => {
render(<App />);
expect(screen.getByText('Hello React')).toBeInTheDocument();
});Answer:
Jest is a JavaScript testing framework commonly used with React. It provides features such as test runners, assertions, mocks, snapshots, and code coverage.
Code Example:
test('adds numbers', () => {
expect(2 + 3).toBe(5);
});Answer:
Axios is a promise-based HTTP client that simplifies API requests. It automatically parses JSON responses, supports interceptors, request cancellation, and better error handling compared to the Fetch API.
Code Example:
import axios from 'axios';
axios.get('/api/users')
.then(res => console.log(res.data))
.catch(err => console.error(err));Answer:
Code splitting divides the application into smaller bundles that are loaded only when needed. This reduces the initial bundle size and improves page load performance.
Code Example:
const Dashboard = React.lazy(() =>
import('./Dashboard')
);Answer:
Use Context API for sharing simple global data such as themes, language, or authentication. Use Redux or Redux Toolkit when managing complex application state with frequent updates and predictable state transitions.
Code Example:
const AuthContext = React.createContext();Answer:
No. Hooks must always be called at the top level of a React functional component or a custom Hook. Calling Hooks inside loops, conditions, or nested functions breaks the Rules of Hooks.
Code Example:
// ❌ Incorrect
if (loggedIn) {
useEffect(() => {});
}
// ✅ Correct
useEffect(() => {}, []);Answer:
Hooks should only be called at the top level of React function components or custom Hooks. They should never be called inside loops, conditions, or nested functions.
Code Example:
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = count.toString();
}, [count]);
}Answer:
Prop drilling is the process of passing props through multiple intermediate components to reach a deeply nested child component. It can make code difficult to maintain and is often solved using Context API or Redux.
Code Example:
App
└── Dashboard
└── Sidebar
└── Profile
└── UserCardAnswer:
Props are read-only values passed from a parent component to a child component. State is managed within a component and can change over time, causing the component to re-render.
Code Example:
function User({ name }) {
const [age, setAge] = useState(25);
return (
<>
<h2>{name}</h2>
<h3>{age}</h3>
</>
);
}Answer:
React provides reusable components, one-way data flow, a Virtual DOM for fast rendering, excellent performance, a large ecosystem, strong community support, and seamless integration with modern tools. It is widely used for building scalable single-page applications (SPAs) and enterprise web applications.
Code Example:
Advantages of React:
✔ Component-Based Architecture
✔ Virtual DOM
✔ JSX
✔ Hooks
✔ Strong Ecosystem
✔ Excellent Performance
✔ Easy Testing