KEMBAR78
React | PDF | Document Object Model | Computer Programming
0% found this document useful (0 votes)
50 views8 pages

React

This document provides a comprehensive overview of beginner to advanced React interview questions and answers. It covers key concepts such as React, SPAs, JSX, components, props, state management, hooks, and more. Additionally, it explains advanced topics like Context API, HOCs, reconciliation, and the React rendering process.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views8 pages

React

This document provides a comprehensive overview of beginner to advanced React interview questions and answers. It covers key concepts such as React, SPAs, JSX, components, props, state management, hooks, and more. Additionally, it explains advanced topics like Context API, HOCs, reconciliation, and the React rendering process.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

🔰 Beginner Level React Interview Questions

Q1. What is React?


React is a JavaScript library created by Facebook for building fast and interactive user interfaces (UIs), especially
single-page applications (SPAs).
Key features:
 Component-based
 Virtual DOM for fast UI updates
 Declarative syntax using JSX

Q2. What is an SPA (Single Page Application)?


An SPA is a web application that loads a single HTML page and dynamically updates the UI without refreshing
the whole page.
Benefits:
 Faster navigation
 Better user experience
React enables SPA behavior using client-side routing (e.g., React Router).

Q3. What is JSX, and how is it different from HTML?


JSX (JavaScript XML) is a syntax extension used in React to write HTML-like code inside JavaScript.
Differences:
 JSX requires camelCase for attributes (e.g., className instead of class)
 You can embed JavaScript using {} in JSX
 JSX is compiled to React.createElement() behind the scenes

Q4. Difference between functional and class components?


Feature Functional Component Class Component
Syntax JavaScript Function ES6 Class
State useState Hook this.state
Lifecycle useEffect Hook lifecycle methods (componentDidMount, etc.)
Boilerplate Less More
Performance Generally faster Slightly heavier

Q5. Difference between stateless and stateful components?


 Stateless components: Don’t manage their own state (e.g., pure functions).
 Stateful components: Manage internal state using useState or class state.
Now, with hooks, even functional components can be stateful.

Q6. What are props in React?


Props (short for properties) are inputs passed from parent to child components.
They are read-only and used to render dynamic content.
<MyComponent name=\"Abhi\" /> // passing 'name' as prop

Q7. Difference between state and props in React?


Feature Props State
Feature Props State
Usage Passed from parent Managed within component
Mutability Immutable (read-only) Mutable (via setState / useState)
Purpose Configure a component Store internal data

Q8. What are controlled vs. uncontrolled components?


 Controlled components: Form elements where React controls their values using state.
 Uncontrolled components: Form elements use the DOM directly via ref.
Controlled example:
<input value={input} onChange={e => setInput(e.target.value)} />

Q9. What is the purpose of the key attribute in React lists?


The key prop is used to uniquely identify elements in a list to help React efficiently update and re-render items
when the list changes.
{items.map(item => <li key={item.id}>{item.name}</li>)}

Q10. What are fragments in React?


React Fragments let you return multiple elements without adding extra nodes to the DOM.
<>
<h1>Hello</h1>
<p>World</p>
</>

🧑💻 Intermediate React Interview Questions


Q11. What is the Virtual DOM?
Virtual DOM is an in-memory representation of the real DOM. React:
1. Updates the Virtual DOM when state changes.
2. Diffs the new and old virtual DOM.
3. Efficiently updates the real DOM with minimum operations.

Q12. What are React lifecycle methods?


Lifecycle methods are functions in class components that get called at specific points:
 Mounting: constructor, componentDidMount
 Updating: shouldComponentUpdate, componentDidUpdate
 Unmounting: componentWillUnmount
With hooks, use useEffect() to handle these lifecycles.

Q13. Explain the useState and useEffect hooks.


useState() – Adds state to functional components:
const [count, setCount] = useState(0);
useEffect() – Runs side effects (API calls, subscriptions):
jsx
CopyEdit
useEffect(() => {
fetchData();
}, []); // Empty array = run once
Q14. What is props drilling in React?
Props drilling is the process of passing data through multiple nested components, even if only the deeply nested
component uses it.
It can be avoided using:
 Context API
 State management libraries (Redux, Zustand)

🧑💻 Advanced React Interview Questions


Q15. What is the Context API?
The Context API allows sharing global data (like theme, auth) without prop drilling.
Usage:
const ThemeContext = React.createContext();
<ThemeContext.Provider value={darkMode}>
<App />
</ThemeContext.Provider>
Access with useContext(ThemeContext)

Q16. What are HOCs (Higher-Order Components)?


An HOC is a function that takes a component and returns a new component with enhanced behavior.
Example:
const withLogger = Wrapped => props => {
console.log('Props:', props);
return <Wrapped {...props} />;
};
Used for cross-cutting concerns like authentication, logging, etc.

Q17. What is Reconciliation in React?


Reconciliation is React’s process of comparing Virtual DOM trees to find differences and updating the DOM
minimally and efficiently.
 Based on heuristics like “same key, same type → update”.
 Different key or type → re-create node.

Q18. Explain React Portals.


React Portals allow rendering a component outside the main DOM hierarchy.
Used for:
 Modals
 Tooltips
 Overlays
ReactDOM.createPortal(child, document.getElementById('modal-root'))

Q19. How does React Router handle navigation in SPAs?


React Router uses the History API to change the URL without refreshing the page.
Main concepts:
 BrowserRouter – wraps the app
 Routes and Route – define paths
 useNavigate – navigate programmatically
=
navigate('/dashboard');

Q20. What is React Strict Mode?


<React.StrictMode> is a wrapper that helps find potential issues in your application:
 Warns about deprecated lifecycle methods
 Detects unexpected side effects
 Helps with detecting unsafe code
Used only in development.

<React.StrictMode>
<App />
</React.StrictMode>

1. What is the difference between React and ReactDOM?


 React is the core library used to build components.
 ReactDOM is used to interact with the DOM and render React components to the browser.

2. What is the difference between React and Angular?


 React is a library focused only on UI, while Angular is a framework with built-in features like routing, form
validation, etc.
 React uses JSX, Angular uses TypeScript and templates.

3. What is the difference between a presentational and container component?


 Presentational components are concerned with how things look (UI).
 Container components handle data and logic, passing props to presentational components.

4. What is reconciliation in React?


 The process by which React updates the DOM efficiently by comparing the new Virtual DOM with the old one.

5. Why should keys be unique in React lists?


 Unique keys help React identify which items changed, added, or removed.
 Reusing keys can lead to unexpected rendering bugs.

6. Why should state not be mutated directly in React?


 Direct mutation doesn’t re-render the component.
 You must use setState or setSomething from useState() to trigger re-render.

7. How do you share data between sibling components?


 Use lifting state up to the common parent.
 Or use Context API or a state management library like Redux.

8. What are synthetic events in React?


 React wraps native DOM events with its own wrapper called SyntheticEvent, providing consistent behavior
across browsers.

9. What are default props in React?


 They are fallback values for props not provided by the parent.
jsx
CopyEdit
MyComponent.defaultProps = {
name: "Guest"
};

10. What is prop-types in React?


 A library to type check props passed to a component.
jsx
CopyEdit
import PropTypes from 'prop-types';

MyComponent.propTypes = {
name: PropTypes.string.isRequired,
};

11. What is the difference between useEffect and useLayoutEffect?


 useEffect runs after the paint (non-blocking).
 useLayoutEffect runs before the browser paints (blocking), useful for layout measurements.

12. How do you prevent unnecessary re-renders?


 Use React.memo() for components.
 Use useCallback() and useMemo() hooks.

13. What is lazy loading in React?


 Dynamically loading components only when they are needed.
js
CopyEdit
const About = React.lazy(() => import('./About'));

14. What is Error Boundary in React?


 A class component using componentDidCatch() and getDerivedStateFromError() to catch JavaScript errors in the
component tree.

15. What is the useRef hook used for?


 To access or store mutable DOM references or values that persist across renders without causing re-renders.

16. What is the difference between useCallback and useMemo?


 useCallback returns a memoized function.
 useMemo returns a memoized value.

17. Can you explain the React rendering process?


 Triggered by setState or props change:
1. Virtual DOM is updated.
2. Diffing algorithm finds changes.
3. Real DOM is updated with minimum operations.

18. What is hydration in React?


 Used during Server Side Rendering (SSR) to attach event listeners to existing HTML from the server.

19. What is React DevTools?


 A Chrome/Firefox extension to inspect React component tree, props, state, hooks, etc.

20. Explain conditional rendering in React.


You can conditionally show content using:
js
CopyEdit
{isLoggedIn ? <Dashboard /> : <Login />}
or with &&:
js
CopyEdit
{isAdmin && <AdminPanel />}

21. What is the difference between mounting and unmounting?


 Mounting: Component is added to the DOM.
 Unmounting: Component is removed from the DOM.
 You can handle cleanup in useEffect's return function or componentWillUnmount.

22. What is a custom hook?


 A reusable hook that abstracts logic from components:
js
CopyEdit
function useCounter() {
const [count, setCount] = useState(0);
return [count, () => setCount(count + 1)];
}

23. Can you use hooks inside loops or conditions?


 ❌ No. Hooks must be called at the top level of the function component, not conditionally or inside loops.

24. Difference between React Native and React?


 React: Builds web UIs.
 React Native: Builds native mobile apps using React concepts.

25. What is the role of Babel and Webpack in React?


 Babel: Transpiles JSX and modern JavaScript to browser-compatible JS.
 Webpack: Bundles modules and assets for deployment.

1. useState
 Purpose: Adds local state to functional components.
 Syntax:
js
CopyEdit
const [count, setCount] = useState(0);
 Usage:
o count is the state variable.
o setCount is the function to update it.
 Example:
jsx
CopyEdit
const [name, setName] = useState('');

2. useEffect
 Purpose: Perform side effects like fetching data, setting up subscriptions, or updating the DOM.
 Syntax:
js
CopyEdit
useEffect(() => {
// side effect
return () => {
// cleanup (optional)
};
}, [dependency]);
 Runs:
o On initial mount.
o On dependency change.
 Example:
jsx
CopyEdit
useEffect(() => {
document.title = `Hello ${name}`;
}, [name]);

3. useContext
 Purpose: Access context value without prop drilling.
 Syntax:
js
CopyEdit
const value = useContext(MyContext);
 Example:
jsx
CopyEdit
const ThemeContext = React.createContext();
const theme = useContext(ThemeContext);

4. useRef
 Purpose:
o Access DOM elements directly.
o Store mutable values that don’t trigger re-renders.
 Syntax:
js
CopyEdit
const inputRef = useRef(null);
 Example:
jsx
CopyEdit
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>

5. useMemo
 Purpose: Memoize expensive computations to avoid recalculations on every render.
 Syntax:
js
CopyEdit
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
 Example:
jsx
CopyEdit
const expensive = useMemo(() => heavyCalc(data), [data]);

6. useCallback
 Purpose: Memoize functions to prevent unnecessary re-creations (useful when passing functions to children).
 Syntax:
js
CopyEdit
const memoizedFn = useCallback(() => doSomething(a), [a]);
 Example:
jsx
CopyEdit
const handleClick = useCallback(() => setCount(count + 1), [count]);

7. useReducer
 Purpose: Alternative to useState for complex state logic (like Redux).
 Syntax:
js
CopyEdit
const [state, dispatch] = useReducer(reducerFn, initialState);
 Example:
jsx
CopyEdit
const reducer = (state, action) => {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
default: return state;
}
};
const [state, dispatch] = useReducer(reducer, { count: 0 });

You might also like