ReactJS Questions
ReactJS Questions
1. What is React.js?
Example:
jsxCopy code
// Initial render
const element = <h1>Hello, World!</h1>;
ReactDOM.render(element, document.getElementById('root'));
// Subsequent update
const updatedElement = <h1>Hello, Universe!</h1>;
ReactDOM.render(updatedElement, document.getElementById('root'));
Virtual DOM
JSX stands for JavaScript XML and allows you to write HTML-like code directly
within JavaScript.
Example:
Components are the building blocks of React applications. They can be either
functional or class-based.
jsxCopy code
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Class components are ES6 classes that extend React.Component . They have a
render() method to return the component's UI.
jsxCopy code
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Class components can have state and lifecycle methods, while functional
components can't.
Props (short for properties) are inputs to React components, allowing data to be
passed from parent components to child components.
jsxCopy code
class Button extends React.Component {
handleClick() {
console.log('Button clicked!');
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
jsxCopy code
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
Lifting state up is a pattern in React where you move the state from a child
component to its parent to share the state among multiple children.
Keys are used to help React identify which items have changed, been added, or
removed in a list, enabling efficient rendering and updating of components.
jsxCopy code
const todos = ['Learn React', 'Build an app', 'Deploy to production'];
13. What is React Router, and how do you use it for navigation?
jsxCopy code
import { BrowserRouter, Route, Link } from 'react-router-dom';
jsxCopy code
class Form extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
console.log('Submitted value:', this.state.value);
}
render() {
return (
<form onSubmit={(event) => this.handleSubmit(event)}>
<input
type="text"
value={this.state.value}
onChange={(event) => this.handleChange(event)}
/>
<button type="submit">Submit</button>
</form>
);
}
}
jsxCopy code
function withLogger(WrappedComponent) {
return class extends React.Component {
componentDidMount() {
console.log('Component is mounted!');
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
16. Explain React hooks and list some commonly used ones.
React hooks are functions that allow functional components to use state and
other React features without using class components. Commonly used hooks
are useState , useEffect , useContext , useReducer , and useCallback .
jsxCopy code
import { useState, useEffect } from 'react';
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
18. Explain the Context API in React and why you would use it.
The Context API is used for managing global state in React applications,
allowing data to be shared without having to pass props manually through all
components.
Data fetching can be done using various methods, such as fetch , Axios, or
using GraphQL clients like Apollo or Relay.
jsxCopy code
import { useEffect, useState } from 'react';
useEffect(() => {
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
21. What are React Fragments, and why are they useful?
23. What are portals in React, and why are they used?
Portals allow you to render components outside the parent DOM hierarchy.
They are useful for modals, tooltips, and other scenarios where you need to
render content at a different DOM location.
Error Boundaries are special React components used to catch JavaScript errors
during rendering, in lifecycle methods, or in constructors of whole component
tree.
jsxCopy code
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error or send it to an error reporting service
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
25. What are the different lifecycle methods in React class components?
jsxCopy code
const MyComponent = React.memo((props) => {
/* component implementation */
});
The key prop is used by React to identify elements uniquely in a list and to
improve performance during updates.
jsxCopy code
const ConditionalComponent = ({ show }) => {
return show ? <div>Show me</div> : null;
};
jsxCopy code
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
You can define default props for a component using the defaultProps property.
jsxCopy code
class Greeting extends React.Component {
// ...
}
Greeting.defaultProps = {
name: 'Guest',
};
component. It should be used with caution as it might lead to XSS attacks if not
handled properly.
jsxCopy code
const htmlString = '<span style="color: red;">Dangerous HTML</span>';
The React.Children utilities allow you to work with the props.children object,
even if it's a single child or an array of children.
jsxCopy code
import React from 'react';
jsxCopy code
const element = React.createElement('h1', null, 'Hello, World!');
Hooks should only be called at the top level of functional components or other
custom hooks, not inside loops, conditions, or nested functions.
Code splitting is a technique to break the application code into smaller chunks
and load them on demand. It improves the initial loading time and performance.
Lazy loading can be achieved using React's lazy function along with dynamic
import() .
jsxCopy code
import React, { lazy, Suspense } from 'react';
method.
jsxCopy code
const MyComponent = () => {
// component implementation
};
MyComponent.displayName = 'MyComponent';
43. How can you prevent the default behavior of an event in React?
jsxCopy code
const handleClick = (event) => {
event.preventDefault();
// Your custom logic here
};
jsxCopy code
import ReactDOM from 'react-dom';
jsxCopy code
const htmlString = '<span style="color: red;">Dangerous HTML</span>';
SSR is a technique where the initial HTML content is generated on the server
and sent to the client, enabling search engines to index the page properly and
improving performance for the first load.
Form handling can be done using controlled components, where form values
are stored in state, or by using form libraries like Formik or React Hook Form.
jsxCopy code
const MyForm = () => {
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
};
jsxCopy code
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
React offers built-in state management using the useState hook. For more
complex state management, you can use libraries like Redux or Mobx.
Hooks are functions that allow you to use state and other React features in
functional components without writing a class.