1. What is React?
Explanation: React is a JavaScript library for building user interfaces, developed by Facebook. It allows developers to build single-page applications with a component-based architecture.
Solution: React enables the creation of reusable UI components that manage their own state, then compose them to make complex user interfaces.
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => <h1>Hello, React!</h1>;
ReactDOM.render(<App />, document.getElementById('root'));
2. What are components in React?
Explanation: Components are the building blocks of a React application. They are JavaScript functions or classes that optionally accept inputs (known as “props”) and return React elements that describe how a section of the UI should appear.
Solution:
import React from 'react';
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;
export default Greeting;
3. What is the difference between a functional component and a class component?
Explanation: Functional components are simpler and defined as JavaScript functions. Class components are ES6 classes that extend React.Component
and have additional features like lifecycle methods.
Solution:
Functional Component:
const Hello = () => <h1>Hello, world!</h1>;
Class Component:
import React, { Component } from 'react';
class Hello extends Component {
render() {
return <h1>Hello, world!</h1>;
}
}
4. What are props in React?
Explanation: Props (short for properties) are inputs to components. They are passed from a parent component to a child component and are used to pass data and event handlers.
Solution:
const Welcome = ({ name }) => <h1>Welcome, {name}!</h1>;
5. What is state in React?
Explanation: State is a built-in React object that is used to store data that changes over time. Each component can have its own state, which is managed within the component.
Solution:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};
6. How do you handle events in React?
Explanation: Events in React are handled using camelCase syntax and passing a function to the event handler attribute.
Solution:
import React from 'react';
const ClickMe = () => {
const handleClick = () => alert('Button clicked!');
return <button onClick={handleClick}>Click me</button>;
};
7. What is the use of useEffect
in React?
Explanation: useEffect
is a Hook that allows you to perform side effects in functional components, such as fetching data, directly manipulating the DOM, and setting up subscriptions.
Solution:
import React, { useState, useEffect } from 'react';
const Example = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};
8. What is useState
in React?
Explanation: useState
is a Hook that lets you add state to functional components. It returns a state variable and a function to update it.
Solution:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};
9. What are keys in React lists?
Explanation: Keys are unique identifiers used by React to track elements in a list. They help React optimize the rendering process by keeping track of which items have changed, been added, or removed.
Solution:
const numbers = [1, 2, 3];
const listItems = numbers.map((number) => <li key={number}>{number}</li>);
10. What is the Virtual DOM?
Explanation: The Virtual DOM is a lightweight copy of the actual DOM. React uses it to optimize updates to the real DOM by comparing the virtual DOM with the real DOM and applying only the necessary changes.
Solution: React automatically handles updates to the DOM using the Virtual DOM.
11. How do you conditionally render elements in React?
Explanation: You can conditionally render elements using JavaScript operators like if
, &&
, or the ternary operator within your component.
Solution:
const Greeting = ({ isLoggedIn }) => (
isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>
);
12. What is context
in React?
Explanation: Context is a way to pass data through the component tree without having to pass props down manually at every level.
Solution:
import React, { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
const ThemedComponent = () => {
const theme = useContext(ThemeContext);
return <div>The theme is {theme}</div>;
};
13. How do you create a context in React?
Explanation: Create a context using React.createContext
and provide a value for it using a Provider
.
Solution:
import React, { createContext, useContext } from 'react';
const MyContext = createContext('default');
const MyComponent = () => {
const value = useContext(MyContext);
return <div>{value}</div>;
};
const App = () => (
<MyContext.Provider value="Hello, World!">
<MyComponent />
</MyContext.Provider>
);
14. What is useReducer
in React?
Explanation: useReducer
is a Hook used for managing complex state logic. It is an alternative to useState
and is preferred when the state depends on previous state values or involves multiple sub-values.
Solution:
import 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:
throw new Error();
}
}
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
};
15. What is the useCallback
Hook used for?
Explanation: useCallback
returns a memoized callback function. It helps avoid recreating functions on every render, which can be beneficial for performance optimization.
Solution:
import React, { useCallback, useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return (
<div>
<p>{count}</p>
<button onClick={handleClick}>Click me</button>
</div>
);
};
16. What is useMemo
used for in React?
Explanation: useMemo
returns a memoized value. It helps optimize performance by recomputing the value only when dependencies change.
Solution:
import React, { useMemo, useState } from 'react';
const ExpensiveComponent = ({ count }) => {
const computeExpensiveValue = (num) => {
console.log('Computing expensive value');
return num * 2;
};
const result = useMemo(() => computeExpensiveValue(count), [count]);
return <div>Computed Value: {result}</div>;
};
17. What is the purpose of useRef
in React?
Explanation: useRef
creates a mutable object that persists across renders. It can be used to access a DOM element directly or to keep a mutable value.
Solution:
import React, { useRef } from 'react';
const MyComponent = () => {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input
ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
};
18. How do you use props.children
in React?
Explanation: props.children
is a special prop that allows components to pass children elements to their output.
Solution:
const Wrapper = ({ children }) => <div className="wrapper">{children}</div>;
const App = () => (
<Wrapper>
<p>This is a child element</p>
</Wrapper>
);
19. What is React.Fragment
used for?
Explanation: React.Fragment
is used to group multiple elements without adding extra nodes to the DOM.
Solution:
import React from 'react';
const List = () => (
<React.Fragment>
<h1>Title</h1>
<p>Content</p>
</React.Fragment>
);
20. How do you handle forms in React?
Explanation: Forms in React are handled using controlled components, where form data is managed by React state.
Solution:
import React, { useState } from 'react';
const Form = () => {
const [value, setValue] = useState('');
const handleChange = (e) => setValue(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
alert('Submitted value: ' + value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={value} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
};
21. What is a controlled component in React?
Explanation: A controlled component is a form element whose value is controlled by React state.
Solution:
import React, { useState } from 'react';
const ControlledInput = () => {
const [value, setValue] = useState('');
const handleChange = (e) => setValue(e.target.value);
return (
<input type="text" value={value} onChange={handleChange} />
);
};
22. What is an uncontrolled component in React?
Explanation: An uncontrolled component is a form element that maintains its own state and is not controlled by React state.
Solution:
import React, { useRef } from 'react';
const UncontrolledInput = () => {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
alert('A name was submitted: ' + inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
};
23. What is ReactDOM.render
used for?
Explanation: ReactDOM.render
is used to render a React element into the DOM.
Solution:
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => <h1>Hello, React!</h1>;
ReactDOM.render(<App />, document.getElementById('root'));
24. How do you pass data between components in React?
Explanation: Data can be passed between components using props, where a parent component passes data to a child component.
Solution:
const Parent = () => <Child message="Hello from parent!" />;
const Child = ({ message }) => <p>{message}</p>;
25. What is component lifecycle in React?
Explanation: The component lifecycle refers to the series of methods that are invoked at different stages of a component’s existence, from creation to destruction.
Solution:
Class Component Lifecycle Methods:
import React, { Component } from 'react';
class MyComponent extends Component {
componentDidMount() {
// Called after the component is mounted
}
componentDidUpdate(prevProps, prevState) {
// Called after the component updates
}
componentWillUnmount() {
// Called before the component is unmounted
}
render() {
return <div>Component Lifecycle</div>;
}
}
Functional Component with useEffect
:
import React, { useEffect } from 'react';
const MyComponent = () => {
useEffect(() => {
// Called after the component is mounted
return () => {
// Called before the component is unmounted
};
}, []);
return <div>Component Lifecycle</div>;
};
26. How do you use useLayoutEffect
?
Explanation: useLayoutEffect
is similar to useEffect
, but it runs synchronously after all DOM mutations. It is used for reading layout from the DOM and synchronously re-rendering.
Solution:
import React, { useLayoutEffect, useRef } from 'react';
const Example = () => {
const ref = useRef(null);
useLayoutEffect(() => {
console.log(ref.current.getBoundingClientRect());
}, []);
return <div ref={ref}>Hello, World!</div>;
};
27. How do you create a custom Hook in React?
Explanation: Custom Hooks allow you to reuse stateful logic between components.
Solution:
import { useState, useEffect } from 'react';
const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return { count, increment, decrement };
};
const CounterComponent = () => {
const { count, increment, decrement } = useCounter();
return (
<div>
<p>{count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
28. How do you handle conditional rendering in JSX?
Explanation: Conditional rendering in JSX can be done using JavaScript operators like if
, &&
, or the ternary operator.
Solution:
const Example = ({ isLoggedIn }) => (
isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>
);
29. How do you perform asynchronous operations in React?
Explanation: Asynchronous operations can be handled inside useEffect
or other lifecycle methods using async/await syntax.
Solution:
import React, { useState, useEffect } from 'react';
const DataFetchingComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
};
fetchData();
}, []);
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};
30. What are controlled vs. uncontrolled components?
Explanation: Controlled components use React state to manage their data, while uncontrolled components store their own data internally.
Solution:
Controlled Component:
import React, { useState } from 'react';
const ControlledForm = () => {
const [value, setValue] = useState('');
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
};
Uncontrolled Component:
import React, { useRef } from 'react';
const UncontrolledForm = () => {
const inputRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
alert('Value: ' + inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} type="text" />
<button type="submit">Submit</button>
</form>
);
};
31. What is useImperativeHandle
used for?
Explanation: useImperativeHandle
is used with forwardRef
to customize the instance value that is exposed to parent components when using ref
.
Solution:
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
}));
return <input ref={inputRef} {...props} />;
});
const Parent = () => {
const inputRef = useRef();
return (
<div>
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
};
32. What is React.StrictMode
used for?
Explanation: React.StrictMode
is a wrapper component used to detect potential problems in an application. It enables additional checks and warnings for its descendants.
Solution:
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => <h1>Hello, React!</h1>;
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
33. What is the purpose of forwardRef
in React?
Explanation: forwardRef
is a higher-order component that allows you to pass refs through a component to one of its children.
Solution:
import React, { forwardRef } from 'react';
const FancyButton = forwardRef((props, ref) => (
<button ref={ref} {...props} />
));
const Parent = () => {
const buttonRef = React.createRef();
return (
<div>
<FancyButton ref={buttonRef}>Click me</FancyButton>
</div>
);
};
34. What is React.memo
?
Explanation: React.memo
is a higher-order component that prevents a component from re-rendering if its props have not changed.
Solution:
import React from 'react';
const ExpensiveComponent = React.memo(({ value }) => {
console.log('Rendering ExpensiveComponent');
return <div>{value}</div>;
});
35. How do you use useContext
?
Explanation: useContext
is a Hook that allows you to consume context values directly in functional components.
Solution:
import React, { createContext, useContext } from 'react';
const MyContext = createContext('default');
const MyComponent = () => {
const value = useContext(MyContext);
return <div>{value}</div>;
};
const App = () => (
<MyContext.Provider value="Hello, World!">
<MyComponent />
</MyContext.Provider>
);
36. How do you use useEffect
for cleanup?
Explanation: You can return a cleanup function from useEffect
to clean up resources such as subscriptions or timers.
Solution:
import React, { useEffect, useState } from 'react';
const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(intervalId); // Cleanup on unmount
}, []);
return <div>Seconds: {seconds}</div>;
};
37. How do you manage component state with hooks?
Explanation: Component state is managed using the useState
Hook, which allows you to declare state variables in functional components.
Solution:
import React, { useState } from 'react';
const Toggle = () => {
const [isOn, setIsOn] = useState(false);
const toggle = () => setIsOn(prev => !prev);
return (
<button onClick={toggle}>
{isOn ? 'ON' : 'OFF'}
</button>
);
};
38. What are React Hooks?
Explanation: Hooks are functions that let you use state and other React features without writing a class.
Solution:
useState
– For state management.useEffect
– For side effects.useContext
– For context consumption.useReducer
– For complex state logic.
39. How do you use useRef
for DOM manipulation?
Explanation: useRef
creates a reference to a DOM element that can be accessed directly to manipulate the element.
Solution:
import React, { useRef } from 'react';
const FocusInput = () => {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
};
40. How do you use useMemo
for performance optimization?
Explanation: useMemo
helps avoid expensive calculations by memoizing the result and recalculating it only when dependencies change.
Solution:
import React, { useMemo, useState } from 'react';
const ExpensiveComputation = ({ number }) => {
const computeExpensiveValue = (num) => {
console.log('Computing expensive value');
return num * 2;
};
const result = useMemo(() => computeExpensiveValue(number), [number]);
return <div>Computed Value: {result}</div>;
};
41. How do you create a form with validation in React?
Explanation: Form validation in React can be handled using state and event handlers to manage and validate form inputs.
Solution:
import React, { useState } from 'react';
const FormWithValidation = () => {
const [value, setValue] = useState('');
const [error, setError] = useState('');
const handleChange = (e) => {
setValue(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
if (!value) {
setError('Value is required');
} else {
setError('');
alert('Submitted');
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={value} onChange={handleChange} />
{error && <p>{error}</p>}
<button type="submit">Submit</button>
</form>
);
};
42. How do you handle multiple form inputs in React?
Explanation: Handle multiple form inputs by managing each input’s state individually or by using a single state object for all inputs.
Solution:
import React, { useState } from 'react';
const MultiInputForm = () => {
const [form, setForm] = useState({ name: '', email: '' });
const handleChange = (e) => {
const { name, value } = e.target;
setForm((prev) => ({ ...prev, [name]: value }));
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${form.name}, Email: ${form.email}`);
};
return (
<form onSubmit={handleSubmit}>
<input
name="name"
value={form.name}
onChange={handleChange}
placeholder="Name"
/>
<input
name="email"
value={form.email}
onChange={handleChange}
placeholder="Email"
/>
<button type="submit">Submit</button>
</form>
);
};
43. What is React.StrictMode
and how is it different from React.Fragment
?
Explanation: React.StrictMode
is a tool for identifying potential problems in an application, while React.Fragment
is used for grouping elements without adding extra nodes to the DOM.
Solution:
React.StrictMode
:
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => <h1>Hello, React!</h1>;
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
React.Fragment
:
import React from 'react';
const List = () => (
<React.Fragment>
<h1>Title</h1>
<p>Content</p>
</React.Fragment>
);
44. What is a higher-order component (HOC) in React?
Explanation: A higher-order component is a function that takes a component and returns a new component with additional props or logic.
Solution:
import React from 'react';
const withEnhancement = (WrappedComponent) => {
return class extends React.Component {
render() {
return <WrappedComponent {...this.props} enhanced />;
}
};
};
const BasicComponent = (props) => <div>{props.enhanced ? 'Enhanced' : 'Basic'}</div>;
const EnhancedComponent = withEnhancement(BasicComponent);
45. What are React hooks and how do they work?
Explanation: React hooks are functions that let you use state and other React features in functional components. They include useState
, useEffect
, useContext
, etc.
Solution:
import React, { useState, useEffect } from 'react';
const Example = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
46. What is useEffect
and how does it work?
Explanation: useEffect
is a Hook that performs side effects in functional components. It runs after every render by default but can be controlled using a dependency array.
Solution:
import React, { useEffect, useState } from 'react';
const Example = () =>
{
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(result => setData(result));
}, []);
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};
47. How do you use useReducer
for state management?
Explanation: useReducer
is a Hook that manages state with a reducer function, useful for handling complex state logic.
Solution:
import React, { useReducer } from 'react';
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
};
48. How do you optimize performance in React applications?
Explanation: Performance can be optimized using techniques such as memoization with useMemo
, React.memo
, lazy loading components, and avoiding unnecessary re-renders.
Solution:
import React, { useMemo, useState } from 'react';
const ExpensiveComponent = React.memo(({ value }) => {
console.log('Rendering ExpensiveComponent');
return <div>{value}</div>;
});
const App = () => {
const [count, setCount] = useState(0);
const value = useMemo(() => count * 2, [count]);
return (
<div>
<ExpensiveComponent value={value} />
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
49. How do you handle events in React?
Explanation: Event handling in React is done using camelCase syntax and functions.
Solution:
import React from 'react';
const EventExample = () => {
const handleClick = () => {
alert('Button clicked');
};
return <button onClick={handleClick}>Click Me</button>;
};
50. How do you create and use context in React?
Explanation: Context allows you to pass data through the component tree without having to pass props manually at every level.
Solution:
import React, { createContext, useContext } from 'react';
const MyContext = createContext('default');
const Component = () => {
const value = useContext(MyContext);
return <div>{value}</div>;
};
const App = () => (
<MyContext.Provider value="Hello, Context!">
<Component />
</MyContext.Provider>
);